{"id":30714006,"url":"https://github.com/ianmayo/python-vs-code-integration","last_synced_at":"2025-09-03T04:41:29.360Z","repository":{"id":312286689,"uuid":"1046987778","full_name":"IanMayo/python-vs-code-integration","owner":"IanMayo","description":"Demonstrator for allowing python code within VS-Code to interact with VS-Code API","archived":false,"fork":false,"pushed_at":"2025-08-29T16:00:26.000Z","size":165,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-08-29T17:26:37.493Z","etag":null,"topics":["python","vs-code","vs-code-extension"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"epl-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/IanMayo.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-08-29T14:53:12.000Z","updated_at":"2025-08-29T16:00:29.000Z","dependencies_parsed_at":"2025-08-29T17:29:49.996Z","dependency_job_id":"87dfccde-d8e6-42e2-bcf4-247534240ca2","html_url":"https://github.com/IanMayo/python-vs-code-integration","commit_stats":null,"previous_names":["ianmayo/python-vs-code-integration"],"tags_count":5,"template":false,"template_full_name":null,"purl":"pkg:github/IanMayo/python-vs-code-integration","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/IanMayo%2Fpython-vs-code-integration","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/IanMayo%2Fpython-vs-code-integration/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/IanMayo%2Fpython-vs-code-integration/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/IanMayo%2Fpython-vs-code-integration/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/IanMayo","download_url":"https://codeload.github.com/IanMayo/python-vs-code-integration/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/IanMayo%2Fpython-vs-code-integration/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":273392282,"owners_count":25097257,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-03T02:00:09.631Z","response_time":76,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["python","vs-code","vs-code-extension"],"created_at":"2025-09-03T04:41:25.560Z","updated_at":"2025-09-03T04:41:29.341Z","avatar_url":"https://github.com/IanMayo.png","language":"Python","readme":"# Python-VS Code Bridge\n\nA 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.\n\n**🎯 Quick Start**: Run `python demo.py` for an interactive demonstration of all capabilities!\n\n## 🎯 Purpose\n\nThis repository provides a **minimum reproducible example** of bidirectional communication between Python and VS Code, demonstrating:\n\n- 📢 Sending notifications to VS Code from Python\n- 📋 Getting information about open editors\n- 📖 Reading text content from specific files\n- ✏️ Modifying text content in the active editor\n\n## 🏗️ Architecture\n\n```mermaid\nsequenceDiagram\n    participant Python as Python Script\n    participant Bridge as VSCodeBridge\n    participant WS as WebSocket\n    participant Server as VS Code Extension\n    participant VSCode as VS Code API\n    \n    Python-\u003e\u003e+Bridge: bridge.notify(\"Hello\")\n    Bridge-\u003e\u003eBridge: Encode to JSON command\n    Note over Bridge: {\"command\": \"notify\", \"params\": {\"message\": \"Hello\"}}\n    Bridge-\u003e\u003e+WS: Send JSON over WebSocket\n    WS-\u003e\u003e+Server: Forward raw message\n    Server-\u003e\u003eServer: Parse JSON \u0026 validate\n    Server-\u003e\u003eServer: Route to handleNotifyCommand()\n    Server-\u003e\u003e+VSCode: vscode.window.showInformationMessage()\n    VSCode--\u003e\u003e-Server: Success/Error\n    Server-\u003e\u003eServer: Create response JSON\n    Note over Server: {\"result\": null} or {\"error\": {...}}\n    Server-\u003e\u003e-WS: Send response JSON\n    WS-\u003e\u003e-Bridge: Forward response\n    Bridge-\u003e\u003eBridge: Parse JSON \u0026 check errors\n    Bridge--\u003e\u003e-Python: Return result or throw exception\n```\n\n### Components\n\n- **VS Code Extension** (`src/`): WebSocket server that handles commands  \n- **Demo Workspace** (`workspace/`): Contains all demo files opened by Extension Development Host\n  - `python_client/`: Python client library\n  - `examples/`: Demonstration scripts\n  - `demo.py`: Interactive demonstration script\n  - Sample files: `test-file.txt`, `sample.js`, `sample.py`\n\n## 🚀 Quick Start\n\n### 1. Install VS Code Extension\n\n```bash\n# Install dependencies\nyarn install\n\n# Compile extension\nyarn compile\n```\n\n### 2. Launch Extension\n\n- Press `F5` in VS Code to launch Extension Development Host\n- The Extension Development Host will open the `workspace/` folder with demo files\n- The extension will start automatically and create a WebSocket server on port 60123\n\n### 3. Install Python Dependencies\n\nIn the **Extension Development Host** window (the one that opened from F5):\n\n1. **Open Terminal in VS Code:**\n   - Press `Ctrl+`` (backtick) or `Cmd+`` on Mac\n   - Or use menu: **Terminal → New Terminal**\n\n2. **Install Python dependencies:**\n   ```bash\n   pip install -r python_client/requirements.txt\n   ```\n\n### 4. Run the Interactive Demo\n\nIn the same terminal in VS Code:\n\n```bash\n# Run the complete interactive demonstration\npython demo.py\n```\n\nThis will walk you through all the bridge capabilities with explanations and real-time demonstrations.\n\n### 5. Or Run Individual Examples\n\n```bash\n# Basic notification\npython examples/basic_notify.py\n\n# Get editor information  \npython examples/editor_info.py\n\n# Text manipulation\npython examples/text_replacement.py\n\n# Complex workflow\npython examples/automated_workflow.py\n```\n\n💡 **Note**: All Python commands should be run in the VS Code terminal within the Extension Development Host window.\n\n## 📡 API Reference\n\n### VS Code → Python Commands\n\nThe extension accepts JSON messages with this structure:\n\n```json\n{\n  \"command\": \"command_name\",\n  \"params\": {\n    // command-specific parameters\n  }\n}\n```\n\n#### Available Commands\n\n| Command | Description | Parameters |\n|---------|-------------|------------|\n| `notify` | Display notification in VS Code | `message`: string |\n| `get_titles_of_active_editors` | Get list of open editors | none |\n| `get_text_from_named_editor` | Get text from specific file | `filename`: string |\n| `set_text_of_active_editor` | Set text in active editor | `text`: string |\n\n### Python Client API\n\n```python\nfrom vscode_bridge import VSCodeBridge\n\nbridge = VSCodeBridge()\n\n# Send notification\nbridge.notify(\"Hello from Python!\")\n\n# Get editor information\neditors = bridge.get_editor_titles()\n\n# Read file content\ncontent = bridge.get_text_from_editor(\"filename.txt\")\n\n# Set active editor content\nbridge.set_active_editor_text(\"New content\")\n```\n\n## 📝 Examples Explained\n\n### 1. Basic Notification (`basic_notify.py`)\nDemonstrates the simplest integration: sending a notification from Python to VS Code.\n\n### 2. Editor Information (`editor_info.py`)\nShows how to query VS Code for information about all currently open editors.\n\n### 3. Text Replacement (`text_replacement.py`)\nDemonstrates reading content from a file and replacing the active editor's content.\n\n### 4. Automated Workflow (`automated_workflow.py`)\nComplex example that combines all APIs to perform automated code analysis:\n- Scans all open files\n- Counts errors, warnings, and TODOs\n- Generates a comprehensive report\n- Displays results in VS Code\n\n## 🔧 Development\n\n### Building the Extension\n\n```bash\n# Development build with sourcemap\nyarn compile\n\n# Watch mode for development\nyarn watch\n\n# Production build (minified)\nyarn vscode:prepublish\n\n# Type checking only\nyarn typecheck\n```\n\n### Testing\n\n1. Launch the extension in VS Code (`F5`)\n2. Open some test files in the Extension Development Host\n3. Run the Python examples from the terminal\n4. Observe notifications and text changes in VS Code\n\n## 📊 Protocol Details\n\n### WebSocket Connection\n- **Port**: 60123 (localhost only)\n- **Protocol**: JSON-based message exchange\n- **Connection**: Single persistent connection per Python client\n\n### Message Format\n\n**Request:**\n```json\n{\n  \"command\": \"notify\",\n  \"params\": {\n    \"message\": \"Hello World\"\n  }\n}\n```\n\n**Success Response:**\n```json\n{\n  \"result\": null\n}\n```\n\n**Error Response:**\n```json\n{\n  \"error\": {\n    \"message\": \"Error description\",\n    \"code\": 400\n  }\n}\n```\n\n## 🎯 Design Pattern Implementation\n\nThis 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.\n\n### Command Pattern Components\n\n1. **Command Interface**: JSON message structure defining `command` and `params`\n2. **Concrete Commands**: Specific commands like `notify`, `get_titles_of_active_editors`\n3. **Invoker**: Python client (`VSCodeBridge`) that creates and sends commands\n4. **Receiver**: VS Code extension (`GenericWebSocketServer`) that executes commands\n5. **Client**: Python scripts that use the bridge to perform operations\n\n### Benefits of Command Pattern\n\n- **Decoupling**: Python scripts don't need to know VS Code API details\n- **Extensibility**: New commands can be added without modifying existing code\n- **Undo/Redo Potential**: Commands could be stored and replayed\n- **Queuing**: Multiple commands can be batched and executed sequentially\n- **Logging**: All command execution can be logged for debugging\n\n\n\n### Command Encoding Process\n\n1. **Python Method Call**: `bridge.notify(\"Hello from Python!\")`\n2. **Command Object Creation** (`vscode_bridge.py:146-152`):\n   ```python\n   command = {\n       \"command\": \"notify\",\n       \"params\": {\"message\": message}\n   }\n   ```\n3. **JSON Serialization** (`vscode_bridge.py:114`): `json.dumps(message)`\n4. **WebSocket Transmission**: Raw JSON string sent over WebSocket connection\n5. **VS Code Reception** (`websocketServer.ts:64`): Buffer converted to string\n6. **JSON Parsing** (`websocketServer.ts:71`): `JSON.parse(message)`\n7. **Command Validation**: Check for required `command` field and valid structure\n\n### Command Decoding \u0026 Execution Process\n\n1. **Command Router** (`websocketServer.ts:183-217`): Switch statement routes to handler\n2. **Parameter Validation**: Each handler validates required parameters\n3. **VS Code API Call**: Handler calls appropriate VS Code API\n4. **Response Generation**: Success/error response object created\n5. **JSON Serialization**: Response serialized to JSON string\n6. **WebSocket Response**: JSON sent back to Python client\n7. **Python Parsing** (`vscode_bridge.py:118`): JSON parsed and errors checked\n8. **Result Extraction**: Return `result` field or raise `VSCodeBridgeError`\n\n### Error Handling Flow\n\nCommands can fail at multiple stages:\n\n- **Connection Errors**: WebSocket connection unavailable\n- **JSON Errors**: Malformed JSON in either direction  \n- **Validation Errors**: Missing or invalid command parameters\n- **Execution Errors**: VS Code API calls fail\n- **Application Errors**: No active editor, file not found, etc.\n\nEach error is encoded as:\n```json\n{\n  \"error\": {\n    \"message\": \"Description of what went wrong\",\n    \"code\": 400|404|500\n  }\n}\n```\n\n## 🎓 Academic Value\n\nThis project demonstrates several important software engineering concepts:\n\n1. **Command Design Pattern**: Encapsulating requests as objects for flexible execution\n2. **Inter-Process Communication**: WebSocket-based messaging between different runtimes\n3. **Protocol Design**: JSON-based command/response protocol with error handling\n4. **Error Propagation**: Comprehensive error management across distributed systems\n5. **Client-Server Architecture**: Clear separation of concerns between components\n6. **Language Integration**: Bridging Python and TypeScript/JavaScript ecosystems\n7. **Serialization/Deserialization**: JSON encoding/decoding for data transmission\n8. **Validation Patterns**: Parameter validation and type checking across boundaries\n\n## 🔄 Extending the Bridge\n\nTo add new commands:\n\n1. **Add command handler in VS Code** (`src/websocketServer.ts`):\n```typescript\ncase 'your_new_command':\n    return await this.handleYourNewCommand(message.params);\n```\n\n2. **Add method to Python client** (`python_client/vscode_bridge.py`):\n```python\ndef your_new_method(self, param: str) -\u003e str:\n    command = {\n        \"command\": \"your_new_command\",\n        \"params\": {\"param\": param}\n    }\n    response = self.send_json_message(command)\n    return response.get('result')\n```\n\n## 📋 Requirements\n\n- **VS Code**: Version 1.74.0 or higher\n- **Node.js**: Version 16.x or higher\n- **Python**: Version 3.7 or higher\n- **Dependencies**: Listed in `package.json` and `requirements.txt`\n\n## 🐛 Troubleshooting\n\n### Common Issues\n\n1. **Port 60123 already in use**: Close other applications using this port\n2. **Connection refused**: Ensure VS Code extension is running\n3. **Import errors in Python**: Verify `websocket-client` is installed\n4. **Extension not loading**: Check VS Code developer console for errors\n\n### Debug Mode\n\nEnable debug logging by setting:\n```python\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\n```\n\n## 📄 License\n\nThis project is provided as an educational example. Use and modify freely for academic and research purposes.\n\n## 🤝 Contributing\n\nThis is a demonstration repository, but improvements and additional examples are welcome!\n\n---\n\n**Next Steps**: Copy this working implementation to a new repository for standalone distribution and further development.","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fianmayo%2Fpython-vs-code-integration","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fianmayo%2Fpython-vs-code-integration","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fianmayo%2Fpython-vs-code-integration/lists"}