mirror of
https://github.com/mhattingpete/claude-skills-marketplace.git
synced 2026-11-18 18:04:26 +00:00
feat(setup): add Claude Code support with config detection (#17)
* feat(setup): add Claude Code support with config detection 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * feat(execution-runtime): add Claude Code direct import support 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * refactor(execution-runtime): remove Claude Desktop support, focus on Claude Code only 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -14,27 +14,36 @@ Execute Python locally with API access. **90-99% token savings** for bulk operat
|
||||
- Iterative processing across many files
|
||||
- User mentions efficiency/performance
|
||||
|
||||
## Check Availability
|
||||
## How to Use
|
||||
|
||||
Tool exists: `mcp__marketplace_execution__execute_python`
|
||||
Use direct Python imports in Claude Code:
|
||||
|
||||
If not available, guide user: `~/.claude/plugins/marketplaces/mhattingpete-claude-skills/execution-runtime/setup.sh`
|
||||
```python
|
||||
from execution_runtime import fs, code, transform, git
|
||||
|
||||
# Code analysis (metadata only!)
|
||||
functions = code.find_functions('app.py', pattern='handle_.*')
|
||||
|
||||
# File operations
|
||||
code_block = fs.copy_lines('source.py', 10, 20)
|
||||
fs.paste_code('target.py', 50, code_block)
|
||||
|
||||
# Bulk transformations
|
||||
result = transform.rename_identifier('.', 'oldName', 'newName', '**/*.py')
|
||||
|
||||
# Git operations
|
||||
git.git_add(['.'])
|
||||
git.git_commit('feat: refactor code')
|
||||
```
|
||||
|
||||
**If not installed:** Run `~/.claude/plugins/marketplaces/mhattingpete-claude-skills/execution-runtime/setup.sh`
|
||||
|
||||
## Available APIs
|
||||
|
||||
```python
|
||||
# Filesystem - returns only what you need
|
||||
from api.filesystem import copy_lines, paste_code, search_replace, batch_copy
|
||||
|
||||
# Code Analysis - returns METADATA only (not source code!)
|
||||
from api.code_analysis import find_functions, find_classes, analyze_dependencies
|
||||
|
||||
# Transformations - bulk refactoring
|
||||
from api.code_transform import rename_identifier, remove_debug_statements, batch_refactor
|
||||
|
||||
# Git operations
|
||||
from api.git_operations import git_status, git_add, git_commit
|
||||
```
|
||||
- **Filesystem** (`fs`): copy_lines, paste_code, search_replace, batch_copy
|
||||
- **Code Analysis** (`code`): find_functions, find_classes, analyze_dependencies - returns METADATA only!
|
||||
- **Transformations** (`transform`): rename_identifier, remove_debug_statements, batch_refactor
|
||||
- **Git** (`git`): git_status, git_add, git_commit, git_push
|
||||
|
||||
## Pattern
|
||||
|
||||
@@ -46,34 +55,33 @@ from api.git_operations import git_status, git_add, git_commit
|
||||
|
||||
**Bulk refactor (50 files):**
|
||||
```python
|
||||
from api.code_transform import rename_identifier
|
||||
result = rename_identifier('.', 'oldName', 'newName', '**/*.py')
|
||||
from execution_runtime import transform
|
||||
result = transform.rename_identifier('.', 'oldName', 'newName', '**/*.py')
|
||||
# Returns: {'files_modified': 50, 'total_replacements': 247}
|
||||
```
|
||||
|
||||
**Extract functions:**
|
||||
```python
|
||||
from api.code_analysis import find_functions
|
||||
from api.filesystem import copy_lines, paste_code
|
||||
from execution_runtime import code, fs
|
||||
|
||||
functions = find_functions('app.py', pattern='.*_util$') # Metadata only!
|
||||
functions = code.find_functions('app.py', pattern='.*_util$') # Metadata only!
|
||||
for func in functions:
|
||||
code = copy_lines('app.py', func['start_line'], func['end_line'])
|
||||
paste_code('utils.py', -1, code)
|
||||
code_block = fs.copy_lines('app.py', func['start_line'], func['end_line'])
|
||||
fs.paste_code('utils.py', -1, code_block)
|
||||
|
||||
result = {'functions_moved': len(functions)}
|
||||
```
|
||||
|
||||
**Code audit (100 files):**
|
||||
```python
|
||||
from api.code_analysis import analyze_dependencies
|
||||
from execution_runtime import code
|
||||
from pathlib import Path
|
||||
|
||||
files = list(Path('.').glob('**/*.py'))
|
||||
issues = []
|
||||
|
||||
for file in files:
|
||||
deps = analyze_dependencies(str(file)) # Metadata only!
|
||||
deps = code.analyze_dependencies(str(file)) # Metadata only!
|
||||
if deps.get('complexity', 0) > 15:
|
||||
issues.append({'file': str(file), 'complexity': deps['complexity']})
|
||||
|
||||
|
||||
+105
-218
@@ -1,83 +1,54 @@
|
||||
# Claude Skills Marketplace - Execution Runtime
|
||||
# Claude Code - Execution Runtime
|
||||
|
||||
**Code execution environment implementing the [Anthropic code execution pattern](https://www.anthropic.com/engineering/code-execution-with-mcp) for 90%+ token savings.**
|
||||
**Python package for Claude Code implementing the [Anthropic code execution pattern](https://www.anthropic.com/engineering/code-execution-with-mcp) for 90%+ token savings.**
|
||||
|
||||
## Overview
|
||||
|
||||
The Execution Runtime enables Claude to execute Python code locally with access to powerful APIs for file operations, code analysis, transformations, and git operations. Instead of loading all code and data through the context window, Claude writes Python scripts that execute locally and return only results—achieving up to **99% token reduction** for complex operations.
|
||||
The Execution Runtime provides pre-built Python APIs for bulk code operations with massive token savings. Instead of loading all code and data through the context window, you write Python scripts that execute locally and return only results—achieving up to **99% token reduction** for complex operations.
|
||||
|
||||
**What Claude Code already provides:** Sandboxing, resource limits, timeouts, directory restrictions
|
||||
|
||||
**What this package adds:** Pre-built APIs for bulk operations, PII/secret masking, metadata-only code analysis
|
||||
|
||||
## Key Benefits
|
||||
|
||||
✅ **90-99% Token Savings** - Process 100 files using 1,000 tokens instead of 100,000
|
||||
✅ **Faster Operations** - Local execution is significantly faster than multiple API round-trips
|
||||
✅ **Faster Operations** - Local execution vs multiple API round-trips
|
||||
✅ **Stateful Workflows** - Resume multi-step refactoring across sessions
|
||||
✅ **Automatic Security** - PII/secret detection and sandboxed execution
|
||||
✅ **Automatic PII Masking** - Secret detection before results return to context
|
||||
✅ **Reusable Skills** - Save transformation functions for future use
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
execution-runtime/
|
||||
├── api/ # Importable API library
|
||||
│ ├── filesystem.py # File operations (copy, paste, search, batch)
|
||||
│ ├── code_analysis.py # AST parsing (returns metadata, not source)
|
||||
│ ├── code_transform.py # Refactoring operations
|
||||
│ └── git_operations.py # Git command wrappers
|
||||
├── mcp-server/
|
||||
│ ├── mcp_server.py # FastMCP server with execution tools
|
||||
│ └── security/
|
||||
│ ├── sandbox.py # RestrictedPython execution environment
|
||||
│ └── pii_detector.py # Automatic secret/PII masking
|
||||
├── pyproject.toml # Dependencies
|
||||
├── setup.sh # One-command installation
|
||||
└── README.md # This file
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
### Quick Setup (Recommended)
|
||||
|
||||
```bash
|
||||
# 1. Install marketplace plugin (if not already installed)
|
||||
/plugin marketplace add mhattingpete/claude-skills-marketplace
|
||||
|
||||
# 2. Run setup script
|
||||
~/.claude/plugins/marketplaces/mhattingpete-claude-skills/execution-runtime/setup.sh
|
||||
```
|
||||
|
||||
The script will:
|
||||
- Detect your OS and Claude installation
|
||||
- Configure MCP server in Claude config
|
||||
- Set up allowed directories for security
|
||||
- Install dependencies
|
||||
|
||||
### Manual Setup
|
||||
|
||||
1. **Add to Claude config** (`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS):
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"marketplace-execution": {
|
||||
"command": "uv",
|
||||
"args": ["run", "python", "~/.claude/plugins/marketplaces/mhattingpete-claude-skills/execution-runtime/mcp-server/mcp_server.py"],
|
||||
"env": {
|
||||
"ALLOWED_DIRECTORIES": "/Users/yourname/Documents,/Users/yourname/Projects",
|
||||
"MASK_SECRETS": "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
2. **Install dependencies**:
|
||||
## Quick Start
|
||||
|
||||
**1. Install the package:**
|
||||
```bash
|
||||
cd ~/.claude/plugins/marketplaces/mhattingpete-claude-skills/execution-runtime
|
||||
uv pip install -e .
|
||||
pip install -e .
|
||||
```
|
||||
|
||||
3. **Restart Claude Code/Desktop**
|
||||
**2. Use in your prompts:**
|
||||
```python
|
||||
from execution_runtime import fs, code, transform, git
|
||||
|
||||
# Example: Find all functions
|
||||
functions = code.find_functions('app.py')
|
||||
print(f"Found {len(functions)} functions")
|
||||
|
||||
# Example: Rename identifier across codebase
|
||||
result = transform.rename_identifier('.', 'old_name', 'new_name', '**/*.py')
|
||||
print(f"Modified {result['files_modified']} files")
|
||||
|
||||
# Example: Copy lines between files
|
||||
code_block = fs.copy_lines('source.py', 10, 20)
|
||||
fs.paste_code('target.py', 50, code_block)
|
||||
|
||||
# Example: PII masking when needed
|
||||
from execution_runtime import mask_secrets
|
||||
result = {'api_key': 'sk_live_abc123'}
|
||||
safe_output = mask_secrets(str(result)) # Masks secrets automatically
|
||||
```
|
||||
|
||||
**That's it!** Claude Code's built-in sandbox handles security, you get the pre-built APIs and token savings.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -100,9 +71,9 @@ User: "Rename getUserData to fetchUserData in all 50 Python files"
|
||||
|
||||
Claude writes Python script:
|
||||
```python
|
||||
from api.code_transform import rename_identifier
|
||||
from execution_runtime import transform
|
||||
|
||||
result = rename_identifier(
|
||||
result = transform.rename_identifier(
|
||||
pattern='.',
|
||||
old_name='getUserData',
|
||||
new_name='fetchUserData',
|
||||
@@ -124,16 +95,15 @@ Total: ~600 tokens ✅ (99.4% savings)
|
||||
### Example 2: Extract Functions to New File
|
||||
|
||||
```python
|
||||
from api.code_analysis import find_functions
|
||||
from api.filesystem import copy_lines, paste_code
|
||||
from execution_runtime import code, fs
|
||||
|
||||
# Find all utility functions (metadata only, no source in context)
|
||||
functions = find_functions('app.py', pattern='.*_util$')
|
||||
functions = code.find_functions('app.py', pattern='.*_util$')
|
||||
|
||||
# Copy each function to utils.py
|
||||
for func in functions:
|
||||
code = copy_lines('app.py', func['start_line'], func['end_line'])
|
||||
paste_code('utils.py', -1, code) # Append to end
|
||||
code_block = fs.copy_lines('app.py', func['start_line'], func['end_line'])
|
||||
fs.paste_code('utils.py', -1, code_block) # Append to end
|
||||
|
||||
result = {
|
||||
"functions_extracted": len(functions),
|
||||
@@ -144,15 +114,15 @@ result = {
|
||||
### Example 3: Code Audit Across 100 Files
|
||||
|
||||
```python
|
||||
from api.code_analysis import analyze_dependencies, find_unused_imports
|
||||
from execution_runtime import code
|
||||
from pathlib import Path
|
||||
|
||||
files = list(Path('.').glob('**/*.py'))
|
||||
|
||||
audit_results = []
|
||||
for file in files:
|
||||
deps = analyze_dependencies(str(file))
|
||||
unused = find_unused_imports(str(file))
|
||||
deps = code.analyze_dependencies(str(file))
|
||||
unused = code.find_unused_imports(str(file))
|
||||
|
||||
if unused or deps['complexity'] > 10:
|
||||
audit_results.append({
|
||||
@@ -170,24 +140,19 @@ result = {
|
||||
|
||||
## Available APIs
|
||||
|
||||
### 1. Filesystem Operations (`api.filesystem`)
|
||||
### 1. Filesystem Operations (`fs`)
|
||||
|
||||
```python
|
||||
from api.filesystem import (
|
||||
read_file, write_file,
|
||||
copy_lines, paste_code,
|
||||
search_replace,
|
||||
batch_copy, batch_transform
|
||||
)
|
||||
from execution_runtime import fs
|
||||
|
||||
# Copy specific lines
|
||||
code = copy_lines('source.py', start_line=10, end_line=20)
|
||||
code = fs.copy_lines('source.py', start_line=10, end_line=20)
|
||||
|
||||
# Paste at line number
|
||||
paste_code('target.py', line_number=50, code=code, create_backup=True)
|
||||
fs.paste_code('target.py', line_number=50, code=code, create_backup=True)
|
||||
|
||||
# Search and replace across files
|
||||
search_replace(
|
||||
fs.search_replace(
|
||||
file_pattern='**/*.py',
|
||||
search='old_function',
|
||||
replace='new_function',
|
||||
@@ -200,45 +165,36 @@ operations = [
|
||||
'target_file': 'b.py', 'target_line': 5},
|
||||
# ... more operations
|
||||
]
|
||||
batch_copy(operations)
|
||||
fs.batch_copy(operations)
|
||||
```
|
||||
|
||||
### 2. Code Analysis (`api.code_analysis`)
|
||||
### 2. Code Analysis (`code`)
|
||||
|
||||
**Returns metadata only, not source code → massive token savings**
|
||||
|
||||
```python
|
||||
from api.code_analysis import (
|
||||
find_functions, find_classes,
|
||||
extract_imports, get_function_calls,
|
||||
analyze_dependencies, find_unused_imports
|
||||
)
|
||||
from execution_runtime import code
|
||||
|
||||
# Find functions (returns line numbers, not code)
|
||||
functions = find_functions('app.py', pattern='handle_.*')
|
||||
functions = code.find_functions('app.py', pattern='handle_.*')
|
||||
# Returns: [{'name': 'handle_request', 'start_line': 45, 'end_line': 60, ...}]
|
||||
|
||||
# Find classes with methods
|
||||
classes = find_classes('models.py')
|
||||
classes = code.find_classes('models.py')
|
||||
# Returns: [{'name': 'User', 'methods': ['__init__', 'save'], ...}]
|
||||
|
||||
# Analyze complexity
|
||||
deps = analyze_dependencies('complex_file.py')
|
||||
deps = code.analyze_dependencies('complex_file.py')
|
||||
# Returns: {'functions': 25, 'complexity': 87, 'lines': 450}
|
||||
```
|
||||
|
||||
### 3. Code Transformation (`api.code_transform`)
|
||||
### 3. Code Transformation (`transform`)
|
||||
|
||||
```python
|
||||
from api.code_transform import (
|
||||
rename_identifier,
|
||||
remove_debug_statements,
|
||||
add_docstrings,
|
||||
batch_refactor
|
||||
)
|
||||
from execution_runtime import transform
|
||||
|
||||
# Rename across entire codebase
|
||||
rename_identifier(
|
||||
transform.rename_identifier(
|
||||
pattern='.',
|
||||
old_name='oldName',
|
||||
new_name='newName',
|
||||
@@ -246,118 +202,84 @@ rename_identifier(
|
||||
)
|
||||
|
||||
# Remove debug prints
|
||||
remove_debug_statements('app.py')
|
||||
transform.remove_debug_statements('app.py')
|
||||
|
||||
# Add docstrings to functions missing them
|
||||
add_docstrings('module.py', style='google')
|
||||
transform.add_docstrings('module.py', style='google')
|
||||
```
|
||||
|
||||
### 4. Git Operations (`api.git_operations`)
|
||||
### 4. Git Operations (`git`)
|
||||
|
||||
```python
|
||||
from api.git_operations import (
|
||||
git_status, git_add, git_commit, git_push,
|
||||
create_branch, git_diff, git_log
|
||||
)
|
||||
from execution_runtime import git
|
||||
|
||||
# Check status
|
||||
status = git_status()
|
||||
status = git.git_status()
|
||||
# Returns: {'files': {'modified': [...], 'untracked': [...]}}
|
||||
|
||||
# Stage and commit
|
||||
git_add(['.'])
|
||||
git_commit('feat: refactor authentication module')
|
||||
git.git_add(['.'])
|
||||
git.git_commit('feat: refactor authentication module')
|
||||
|
||||
# Create branch and push
|
||||
create_branch('feature/new-auth', checkout=True)
|
||||
git_push('origin', 'feature/new-auth')
|
||||
git.create_branch('feature/new-auth', checkout=True)
|
||||
git.git_push('origin', 'feature/new-auth')
|
||||
```
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### Stateful Refactoring Sessions
|
||||
|
||||
For complex multi-step operations that might be interrupted:
|
||||
### 5. Sessions and Skills
|
||||
|
||||
```python
|
||||
# Create session
|
||||
session = create_refactoring_session(
|
||||
"modernize-codebase",
|
||||
"Update to Python 3.11+ syntax"
|
||||
)
|
||||
from execution_runtime import Session, save_skill, load_skill
|
||||
|
||||
# Process files and save progress
|
||||
for i, file in enumerate(files):
|
||||
# ... do work ...
|
||||
# Create stateful session for complex work
|
||||
session = Session("modernize-codebase", "Update to Python 3.11+ syntax")
|
||||
|
||||
if i % 10 == 0:
|
||||
save_session_state(session['id'], {
|
||||
'processed': files[:i],
|
||||
'remaining': files[i:],
|
||||
'errors': errors
|
||||
})
|
||||
```
|
||||
# Save progress periodically
|
||||
session.save_state({
|
||||
'processed': files[:10],
|
||||
'remaining': files[10:],
|
||||
'errors': []
|
||||
})
|
||||
|
||||
If interrupted, resume later by loading session state.
|
||||
# Resume later
|
||||
state = session.load_state()
|
||||
print(f"Processed: {state['processed']}")
|
||||
|
||||
### Reusable Transformation Skills
|
||||
|
||||
Save frequently-used transformations:
|
||||
|
||||
```python
|
||||
save_reusable_skill(
|
||||
# Save reusable transformation skill
|
||||
save_skill(
|
||||
name="remove_debug_logs",
|
||||
code="""
|
||||
def transform(code):
|
||||
import re
|
||||
# Remove print statements
|
||||
code = re.sub(r'^\\s*print\\(.*\\)\\n?', '', code, flags=re.MULTILINE)
|
||||
# Remove pdb
|
||||
code = re.sub(r'^\\s*import pdb.*\\n?', '', code, flags=re.MULTILINE)
|
||||
code = re.sub(r'^\\s*pdb\\.set_trace\\(\\)\\n?', '', code, flags=re.MULTILINE)
|
||||
return code
|
||||
""",
|
||||
description="Remove debug print and pdb statements"
|
||||
description="Remove debug print statements"
|
||||
)
|
||||
|
||||
# Use in future sessions
|
||||
from skills.remove_debug_logs import transform
|
||||
cleaned_code = transform(original_code)
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
### Sandboxed Execution
|
||||
- **RestrictedPython** environment
|
||||
- **Resource limits**: 30s timeout, 256MB memory
|
||||
- **Restricted imports**: Only `api.*` and safe stdlib modules
|
||||
- **No dangerous builtins**: `eval`, `exec`, `__import__` disabled
|
||||
**Claude Code handles:** Sandboxing, resource limits, timeouts, directory restrictions
|
||||
|
||||
**This package adds:**
|
||||
|
||||
### Automatic PII/Secret Masking
|
||||
|
||||
All execution results are automatically scanned for:
|
||||
```python
|
||||
from execution_runtime import mask_secrets
|
||||
|
||||
# Mask sensitive data before returning to context
|
||||
result = {'api_key': 'sk_live_abc123xyz', 'status': 'success'}
|
||||
safe_output = mask_secrets(str(result))
|
||||
# Returns: {'api_key': '[REDACTED_API_KEY]', 'status': 'success'}
|
||||
```
|
||||
|
||||
Automatically detects and masks:
|
||||
- API keys, tokens, passwords
|
||||
- AWS/GCP/GitHub credentials
|
||||
- Private keys, JWT tokens
|
||||
- Database URLs with credentials
|
||||
- (Optional) Emails, phone numbers, SSNs, credit cards
|
||||
|
||||
Example:
|
||||
```python
|
||||
# Your code contains:
|
||||
api_key = "sk_live_abc123xyz"
|
||||
|
||||
# Results automatically masked:
|
||||
api_key = "[REDACTED_API_KEY]"
|
||||
```
|
||||
|
||||
### Directory Restrictions
|
||||
|
||||
Only files within `ALLOWED_DIRECTORIES` can be accessed. Configure in setup or `.env`:
|
||||
|
||||
```bash
|
||||
ALLOWED_DIRECTORIES=/Users/you/Documents,/Users/you/Projects
|
||||
```
|
||||
|
||||
## Performance Benchmarks
|
||||
|
||||
@@ -371,56 +293,21 @@ ALLOWED_DIRECTORIES=/Users/you/Documents,/Users/you/Projects
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "Module 'api' not found"
|
||||
### "Module 'execution_runtime' not found"
|
||||
|
||||
Ensure MCP server is running and Python path is configured. Restart Claude.
|
||||
|
||||
### "Import not allowed in sandbox"
|
||||
|
||||
Only `api.*` and safe stdlib modules are allowed. Check allowed imports list.
|
||||
Install the package:
|
||||
```bash
|
||||
cd ~/.claude/plugins/marketplaces/mhattingpete-claude-skills/execution-runtime
|
||||
pip install -e .
|
||||
```
|
||||
|
||||
### "Permission denied" errors
|
||||
|
||||
Verify `ALLOWED_DIRECTORIES` includes the files you're trying to access.
|
||||
Claude Code's sandbox controls file access. Ensure files are in an allowed directory.
|
||||
|
||||
### MCP server not starting
|
||||
### Import errors
|
||||
|
||||
Check logs at `~/.claude/logs/execution-runtime.log`
|
||||
|
||||
## Configuration
|
||||
|
||||
Create `.env` file in execution-runtime directory:
|
||||
|
||||
```bash
|
||||
# Security
|
||||
ALLOWED_DIRECTORIES=/Users/you/Documents,/Users/you/Projects
|
||||
MASK_SECRETS=true
|
||||
AGGRESSIVE_MASKING=false # Also mask emails, IPs, etc.
|
||||
|
||||
# Resource Limits
|
||||
EXECUTION_TIMEOUT=30
|
||||
MEMORY_LIMIT_MB=256
|
||||
|
||||
# Logging
|
||||
LOG_LEVEL=INFO
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
### Running Tests
|
||||
|
||||
```bash
|
||||
cd execution-runtime
|
||||
uv pip install -e ".[dev]"
|
||||
pytest
|
||||
```
|
||||
|
||||
### Adding New APIs
|
||||
|
||||
1. Create module in `api/` directory
|
||||
2. Add imports to `api/__init__.py`
|
||||
3. Update `mcp_server.py` to expose in `list_available_apis`
|
||||
4. Write tests and documentation
|
||||
The package uses `from execution_runtime import fs, code, transform, git`. If you see import errors, verify the package is installed correctly.
|
||||
|
||||
## Resources
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
Claude Code Execution Runtime.
|
||||
|
||||
Provides high-level APIs for bulk code operations with 90%+ token savings.
|
||||
|
||||
Quick start:
|
||||
from execution_runtime import fs, code, transform, git
|
||||
|
||||
# Find all functions (metadata only - no source in context!)
|
||||
functions = code.find_functions('app.py', pattern='handle_.*')
|
||||
|
||||
# Rename identifier across codebase
|
||||
result = transform.rename_identifier('.', 'oldName', 'newName', '**/*.py')
|
||||
|
||||
# Copy lines between files
|
||||
code_block = fs.copy_lines('source.py', 10, 20)
|
||||
fs.paste_code('target.py', 50, code_block)
|
||||
|
||||
# Git operations
|
||||
git.git_add(['.'])
|
||||
git.git_commit('feat: refactor code')
|
||||
|
||||
For automatic PII/secret masking:
|
||||
from execution_runtime import mask_secrets
|
||||
|
||||
result = {'api_key': 'sk_live_abc123'}
|
||||
masked = mask_secrets(str(result))
|
||||
# Returns: {'api_key': '[REDACTED_API_KEY]'}
|
||||
"""
|
||||
|
||||
__version__ = "2.0.0"
|
||||
__author__ = "Anthropic"
|
||||
|
||||
# Import API modules with convenient aliases
|
||||
# Note: api package is at parent level for MCP server compatibility
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Add parent directory to path to import from api/
|
||||
_parent_dir = Path(__file__).parent.parent
|
||||
if str(_parent_dir) not in sys.path:
|
||||
sys.path.insert(0, str(_parent_dir))
|
||||
|
||||
from api import (
|
||||
filesystem as fs,
|
||||
code_analysis as code,
|
||||
code_transform as transform,
|
||||
git_operations as git
|
||||
)
|
||||
|
||||
# Import security utilities (will be created in execution_runtime package)
|
||||
try:
|
||||
from .security.pii_detector import mask_secrets, PIIDetector, mask_result
|
||||
except ImportError:
|
||||
# Fallback to mcp-server location during transition
|
||||
from mcp_server.security.pii_detector import mask_secrets, PIIDetector, mask_result as mask_result_fn
|
||||
mask_result = mask_result_fn
|
||||
|
||||
# Import session and skills management (will be created)
|
||||
try:
|
||||
from .sessions import Session, create_session, load_session
|
||||
from .skills import save_skill, load_skill, list_skills
|
||||
except ImportError:
|
||||
# Temporarily unavailable during migration
|
||||
Session = None
|
||||
create_session = None
|
||||
load_session = None
|
||||
save_skill = None
|
||||
load_skill = None
|
||||
list_skills = None
|
||||
|
||||
__all__ = [
|
||||
# Version
|
||||
'__version__',
|
||||
|
||||
# API modules (aliased)
|
||||
'fs',
|
||||
'code',
|
||||
'transform',
|
||||
'git',
|
||||
|
||||
# Security
|
||||
'mask_secrets',
|
||||
'PIIDetector',
|
||||
'mask_result',
|
||||
|
||||
# Session management
|
||||
'Session',
|
||||
'create_session',
|
||||
'load_session',
|
||||
|
||||
# Skills management
|
||||
'save_skill',
|
||||
'load_skill',
|
||||
'list_skills',
|
||||
]
|
||||
@@ -0,0 +1,17 @@
|
||||
"""
|
||||
Security utilities for execution runtime.
|
||||
|
||||
Provides PII/secret detection and masking capabilities.
|
||||
"""
|
||||
|
||||
from .pii_detector import (
|
||||
PIIDetector,
|
||||
mask_secrets,
|
||||
mask_result
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'PIIDetector',
|
||||
'mask_secrets',
|
||||
'mask_result',
|
||||
]
|
||||
@@ -0,0 +1,170 @@
|
||||
"""
|
||||
Lightweight import restrictions for code execution.
|
||||
|
||||
Provides import whitelisting without full sandboxing, since Claude Code
|
||||
already handles resource limits, timeouts, and filesystem restrictions.
|
||||
"""
|
||||
|
||||
from typing import List, Set
|
||||
|
||||
|
||||
class ImportGuard:
|
||||
"""
|
||||
Lightweight import restriction without full sandboxing.
|
||||
|
||||
For Claude Code, this provides an additional layer of import restrictions
|
||||
while relying on Claude Code's existing sandbox for resource management.
|
||||
"""
|
||||
|
||||
# Allowed standard library modules
|
||||
ALLOWED_STDLIB_MODULES: Set[str] = {
|
||||
're', 'json', 'datetime', 'math', 'collections',
|
||||
'itertools', 'functools', 'operator', 'pathlib',
|
||||
'typing', 'dataclasses', 'enum', 'copy', 'heapq',
|
||||
'bisect', 'array', 'weakref', 'types', 'string',
|
||||
'textwrap', 'unicodedata', 'stringprep', 'difflib',
|
||||
'hashlib', 'hmac', 'secrets', 'os.path', 'fnmatch',
|
||||
'linecache', 'tempfile', 'glob', 'shutil', 'pprint',
|
||||
'contextlib', 'abc', 'atexit', 'traceback', 'time',
|
||||
'argparse', 'logging', 'platform', 'errno',
|
||||
'io', 'codecs', 'ast', 'inspect', 'dis'
|
||||
}
|
||||
|
||||
def __init__(self, allowed_patterns: List[str] = None):
|
||||
"""
|
||||
Initialize import guard.
|
||||
|
||||
Args:
|
||||
allowed_patterns: Additional allowed import patterns (e.g., ['api.*', 'execution_runtime.*'])
|
||||
"""
|
||||
self.allowed_patterns = allowed_patterns or ['api.*', 'execution_runtime.*']
|
||||
|
||||
def is_allowed(self, module_name: str) -> bool:
|
||||
"""
|
||||
Check if module import is allowed.
|
||||
|
||||
Args:
|
||||
module_name: Full module name to check
|
||||
|
||||
Returns:
|
||||
True if allowed, False otherwise
|
||||
|
||||
Example:
|
||||
>>> guard = ImportGuard()
|
||||
>>> guard.is_allowed('json')
|
||||
True
|
||||
>>> guard.is_allowed('api.filesystem')
|
||||
True
|
||||
>>> guard.is_allowed('os') # os is restricted by default
|
||||
False
|
||||
"""
|
||||
base_module = module_name.split('.')[0]
|
||||
|
||||
# Check stdlib whitelist
|
||||
if base_module in self.ALLOWED_STDLIB_MODULES:
|
||||
return True
|
||||
|
||||
# Check if full module name is in stdlib (for os.path, etc.)
|
||||
if module_name in self.ALLOWED_STDLIB_MODULES:
|
||||
return True
|
||||
|
||||
# Check patterns
|
||||
for pattern in self.allowed_patterns:
|
||||
if pattern.endswith('.*'):
|
||||
# Wildcard pattern like 'api.*'
|
||||
prefix = pattern[:-2]
|
||||
if module_name.startswith(prefix + '.') or module_name == prefix:
|
||||
return True
|
||||
elif pattern == module_name:
|
||||
# Exact match
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def restrict_import(self, module_name: str):
|
||||
"""
|
||||
Raise ImportError if module not allowed.
|
||||
|
||||
Args:
|
||||
module_name: Module name to check
|
||||
|
||||
Raises:
|
||||
ImportError: If module not in whitelist
|
||||
|
||||
Example:
|
||||
>>> guard = ImportGuard()
|
||||
>>> guard.restrict_import('json') # OK
|
||||
>>> guard.restrict_import('os') # Raises ImportError
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ImportError: Import of 'os' not allowed...
|
||||
"""
|
||||
if not self.is_allowed(module_name):
|
||||
raise ImportError(
|
||||
f"Import of '{module_name}' not allowed. "
|
||||
f"Allowed stdlib: {sorted(self.ALLOWED_STDLIB_MODULES)[:10]}... "
|
||||
f"and patterns: {self.allowed_patterns}"
|
||||
)
|
||||
|
||||
def create_restricted_import(self):
|
||||
"""
|
||||
Create a restricted __import__ function.
|
||||
|
||||
Returns:
|
||||
Function that can be used to replace __import__
|
||||
|
||||
Example:
|
||||
>>> guard = ImportGuard()
|
||||
>>> restricted_import = guard.create_restricted_import()
|
||||
>>> # Use in restricted globals:
|
||||
>>> globals_dict = {'__import__': restricted_import, ...}
|
||||
"""
|
||||
def restricted_import(name, globals=None, locals=None, fromlist=(), level=0):
|
||||
"""Restricted import that checks whitelist."""
|
||||
self.restrict_import(name)
|
||||
return __import__(name, globals, locals, fromlist, level)
|
||||
|
||||
return restricted_import
|
||||
|
||||
|
||||
# Default instance for common use
|
||||
default_guard = ImportGuard()
|
||||
|
||||
|
||||
def is_import_allowed(module_name: str) -> bool:
|
||||
"""
|
||||
Check if module import is allowed using default guard.
|
||||
|
||||
Args:
|
||||
module_name: Module name to check
|
||||
|
||||
Returns:
|
||||
True if allowed, False otherwise
|
||||
|
||||
Example:
|
||||
>>> is_import_allowed('json')
|
||||
True
|
||||
>>> is_import_allowed('subprocess')
|
||||
False
|
||||
"""
|
||||
return default_guard.is_allowed(module_name)
|
||||
|
||||
|
||||
def restrict_import(module_name: str):
|
||||
"""
|
||||
Raise ImportError if module not allowed (using default guard).
|
||||
|
||||
Args:
|
||||
module_name: Module name to check
|
||||
|
||||
Raises:
|
||||
ImportError: If module not in whitelist
|
||||
|
||||
Example:
|
||||
>>> restrict_import('json') # OK
|
||||
>>> restrict_import('subprocess') # Raises ImportError
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ImportError: Import of 'subprocess' not allowed...
|
||||
"""
|
||||
default_guard.restrict_import(module_name)
|
||||
@@ -0,0 +1,268 @@
|
||||
"""
|
||||
PII and Secret Detection
|
||||
|
||||
Automatically detect and mask sensitive information before it reaches the model context.
|
||||
"""
|
||||
|
||||
import re
|
||||
from typing import Dict, List, Tuple, Optional
|
||||
|
||||
|
||||
class PIIDetector:
|
||||
"""
|
||||
Detect and mask personally identifiable information and secrets.
|
||||
"""
|
||||
|
||||
# Patterns for different types of sensitive data
|
||||
PATTERNS = {
|
||||
'api_key': [
|
||||
r'api[_-]?key["\']?\s*[:=]\s*["\']([a-zA-Z0-9_\-]{20,})["\']',
|
||||
r'apikey["\']?\s*[:=]\s*["\']([a-zA-Z0-9_\-]{20,})["\']',
|
||||
],
|
||||
'aws_key': [
|
||||
r'AKIA[0-9A-Z]{16}', # AWS Access Key ID
|
||||
r'aws[_-]?access[_-]?key[_-]?id["\']?\s*[:=]\s*["\']([A-Z0-9]{20})["\']',
|
||||
r'aws[_-]?secret[_-]?access[_-]?key["\']?\s*[:=]\s*["\']([A-Za-z0-9/+=]{40})["\']',
|
||||
],
|
||||
'github_token': [
|
||||
r'ghp_[a-zA-Z0-9]{36}', # GitHub Personal Access Token
|
||||
r'gho_[a-zA-Z0-9]{36}', # GitHub OAuth Token
|
||||
r'ghu_[a-zA-Z0-9]{36}', # GitHub User Token
|
||||
r'ghs_[a-zA-Z0-9]{36}', # GitHub Server Token
|
||||
r'ghr_[a-zA-Z0-9]{36}', # GitHub Refresh Token
|
||||
],
|
||||
'google_api_key': [
|
||||
r'AIza[0-9A-Za-z\-_]{35}',
|
||||
],
|
||||
'slack_token': [
|
||||
r'xox[pboa]-[0-9]{11,12}-[0-9]{11,12}-[0-9a-zA-Z]{24,32}',
|
||||
],
|
||||
'generic_secret': [
|
||||
r'secret["\']?\s*[:=]\s*["\']([a-zA-Z0-9_\-/+=]{20,})["\']',
|
||||
r'password["\']?\s*[:=]\s*["\']([^"\']{8,})["\']',
|
||||
r'token["\']?\s*[:=]\s*["\']([a-zA-Z0-9_\-/+=]{20,})["\']',
|
||||
],
|
||||
'private_key': [
|
||||
r'-----BEGIN (?:RSA |DSA |EC )?PRIVATE KEY-----',
|
||||
r'-----BEGIN OPENSSH PRIVATE KEY-----',
|
||||
],
|
||||
'email': [
|
||||
r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
|
||||
],
|
||||
'phone': [
|
||||
r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b', # US phone numbers
|
||||
r'\+\d{1,3}[-.]?\d{1,14}\b', # International
|
||||
],
|
||||
'ssn': [
|
||||
r'\b\d{3}-\d{2}-\d{4}\b', # US SSN
|
||||
],
|
||||
'credit_card': [
|
||||
r'\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b', # Credit card
|
||||
],
|
||||
'ip_address': [
|
||||
r'\b(?:\d{1,3}\.){3}\d{1,3}\b', # IPv4
|
||||
],
|
||||
'jwt_token': [
|
||||
r'eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*',
|
||||
],
|
||||
'stripe_key': [
|
||||
r'sk_live_[0-9a-zA-Z]{24}',
|
||||
r'pk_live_[0-9a-zA-Z]{24}',
|
||||
],
|
||||
'database_url': [
|
||||
r'(?:postgres|mysql|mongodb)://[^:]+:[^@]+@[^/]+/[^\s]+',
|
||||
],
|
||||
}
|
||||
|
||||
# Mask formats for different types
|
||||
MASK_FORMATS = {
|
||||
'api_key': '[REDACTED_API_KEY]',
|
||||
'aws_key': '[REDACTED_AWS_KEY]',
|
||||
'github_token': '[REDACTED_GITHUB_TOKEN]',
|
||||
'google_api_key': '[REDACTED_GOOGLE_API_KEY]',
|
||||
'slack_token': '[REDACTED_SLACK_TOKEN]',
|
||||
'generic_secret': '[REDACTED_SECRET]',
|
||||
'private_key': '[REDACTED_PRIVATE_KEY]',
|
||||
'email': '[EMAIL_REDACTED]',
|
||||
'phone': '[PHONE_REDACTED]',
|
||||
'ssn': '[SSN_REDACTED]',
|
||||
'credit_card': '[CARD_REDACTED]',
|
||||
'ip_address': '[IP_REDACTED]',
|
||||
'jwt_token': '[JWT_REDACTED]',
|
||||
'stripe_key': '[REDACTED_STRIPE_KEY]',
|
||||
'database_url': '[REDACTED_DATABASE_URL]',
|
||||
}
|
||||
|
||||
def __init__(self, enabled_detectors: Optional[List[str]] = None):
|
||||
"""
|
||||
Initialize PII detector.
|
||||
|
||||
Args:
|
||||
enabled_detectors: List of detector types to enable (None = all)
|
||||
"""
|
||||
self.enabled_detectors = enabled_detectors or list(self.PATTERNS.keys())
|
||||
|
||||
def detect(self, text: str) -> List[Dict]:
|
||||
"""
|
||||
Detect sensitive information in text.
|
||||
|
||||
Args:
|
||||
text: Text to scan
|
||||
|
||||
Returns:
|
||||
List of detected items with type, match, and position
|
||||
"""
|
||||
detections = []
|
||||
|
||||
for detector_type in self.enabled_detectors:
|
||||
if detector_type not in self.PATTERNS:
|
||||
continue
|
||||
|
||||
patterns = self.PATTERNS[detector_type]
|
||||
|
||||
for pattern in patterns:
|
||||
for match in re.finditer(pattern, text, re.IGNORECASE):
|
||||
detections.append({
|
||||
'type': detector_type,
|
||||
'match': match.group(0),
|
||||
'start': match.start(),
|
||||
'end': match.end(),
|
||||
'line': text[:match.start()].count('\n') + 1
|
||||
})
|
||||
|
||||
return detections
|
||||
|
||||
def mask(self, text: str, detector_types: Optional[List[str]] = None) -> Tuple[str, List[Dict]]:
|
||||
"""
|
||||
Mask sensitive information in text.
|
||||
|
||||
Args:
|
||||
text: Text to mask
|
||||
detector_types: Specific detector types to use (None = all enabled)
|
||||
|
||||
Returns:
|
||||
Tuple of (masked_text, list_of_detections)
|
||||
"""
|
||||
detectors_to_use = detector_types or self.enabled_detectors
|
||||
detections = []
|
||||
masked_text = text
|
||||
|
||||
# Sort detections by position (reverse) to maintain indices during replacement
|
||||
all_detections = self.detect(text)
|
||||
all_detections = [d for d in all_detections if d['type'] in detectors_to_use]
|
||||
all_detections.sort(key=lambda x: x['start'], reverse=True)
|
||||
|
||||
for detection in all_detections:
|
||||
mask_format = self.MASK_FORMATS.get(detection['type'], '[REDACTED]')
|
||||
|
||||
# Replace the match with mask
|
||||
masked_text = (
|
||||
masked_text[:detection['start']] +
|
||||
mask_format +
|
||||
masked_text[detection['end']:]
|
||||
)
|
||||
|
||||
detections.append(detection)
|
||||
|
||||
return masked_text, detections
|
||||
|
||||
def scan_file(self, file_path: str) -> Dict:
|
||||
"""
|
||||
Scan file for sensitive information.
|
||||
|
||||
Args:
|
||||
file_path: Path to file to scan
|
||||
|
||||
Returns:
|
||||
Dict with detections and recommendations
|
||||
"""
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
|
||||
detections = self.detect(content)
|
||||
|
||||
return {
|
||||
'file': file_path,
|
||||
'status': 'success',
|
||||
'detections': detections,
|
||||
'count': len(detections),
|
||||
'types': list(set(d['type'] for d in detections))
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return {
|
||||
'file': file_path,
|
||||
'status': 'error',
|
||||
'error': str(e)
|
||||
}
|
||||
|
||||
def mask_result(self, result: any, aggressive: bool = False) -> any:
|
||||
"""
|
||||
Mask sensitive information in execution results before returning to model.
|
||||
|
||||
Args:
|
||||
result: Result to mask (string, dict, list, etc.)
|
||||
aggressive: Use aggressive masking (emails, IPs, etc.)
|
||||
|
||||
Returns:
|
||||
Masked result
|
||||
"""
|
||||
if isinstance(result, str):
|
||||
# Choose detectors based on aggressiveness
|
||||
if aggressive:
|
||||
detectors = self.enabled_detectors
|
||||
else:
|
||||
# Only mask secrets/credentials, not general PII
|
||||
detectors = [
|
||||
'api_key', 'aws_key', 'github_token', 'google_api_key',
|
||||
'slack_token', 'generic_secret', 'private_key', 'jwt_token',
|
||||
'stripe_key', 'database_url'
|
||||
]
|
||||
|
||||
masked_text, _ = self.mask(result, detectors)
|
||||
return masked_text
|
||||
|
||||
elif isinstance(result, dict):
|
||||
return {k: self.mask_result(v, aggressive) for k, v in result.items()}
|
||||
|
||||
elif isinstance(result, list):
|
||||
return [self.mask_result(item, aggressive) for item in result]
|
||||
|
||||
else:
|
||||
return result
|
||||
|
||||
|
||||
# Global detector instance
|
||||
_default_detector = PIIDetector()
|
||||
|
||||
|
||||
def mask_secrets(text: str) -> str:
|
||||
"""
|
||||
Quick function to mask secrets in text.
|
||||
|
||||
Args:
|
||||
text: Text to mask
|
||||
|
||||
Returns:
|
||||
Masked text
|
||||
"""
|
||||
masked, _ = _default_detector.mask(text, detector_types=[
|
||||
'api_key', 'aws_key', 'github_token', 'google_api_key',
|
||||
'slack_token', 'generic_secret', 'private_key', 'jwt_token',
|
||||
'stripe_key', 'database_url'
|
||||
])
|
||||
return masked
|
||||
|
||||
|
||||
def detect_secrets(text: str) -> List[Dict]:
|
||||
"""
|
||||
Quick function to detect secrets in text.
|
||||
|
||||
Args:
|
||||
text: Text to scan
|
||||
|
||||
Returns:
|
||||
List of detections
|
||||
"""
|
||||
return _default_detector.detect(text)
|
||||
@@ -0,0 +1,196 @@
|
||||
"""
|
||||
Session management for multi-step refactoring operations.
|
||||
|
||||
Stateful sessions allow complex refactoring work to be saved and resumed if interrupted.
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
from typing import Dict, Optional, List
|
||||
|
||||
|
||||
SESSIONS_DIR = Path.home() / ".claude" / "execution-runtime" / "sessions"
|
||||
|
||||
|
||||
class Session:
|
||||
"""
|
||||
Stateful refactoring session for multi-step operations.
|
||||
|
||||
Example:
|
||||
>>> session = Session("modernize-codebase", "Update to Python 3.11+ syntax")
|
||||
>>> session.save_state({'processed': ['a.py', 'b.py'], 'remaining': ['c.py']})
|
||||
>>> state = session.load_state()
|
||||
>>> print(state['processed'])
|
||||
['a.py', 'b.py']
|
||||
"""
|
||||
|
||||
def __init__(self, name: str, description: str = ""):
|
||||
"""
|
||||
Create or load session.
|
||||
|
||||
Args:
|
||||
name: Unique session identifier
|
||||
description: Optional description of the refactoring work
|
||||
"""
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.session_file = SESSIONS_DIR / f"{name}.json"
|
||||
|
||||
SESSIONS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if not self.session_file.exists():
|
||||
self._create_new()
|
||||
|
||||
def _create_new(self):
|
||||
"""Create new session file."""
|
||||
data = {
|
||||
"name": self.name,
|
||||
"description": self.description,
|
||||
"created_at": datetime.now().isoformat(),
|
||||
"state": {},
|
||||
"history": []
|
||||
}
|
||||
self.session_file.write_text(json.dumps(data, indent=2))
|
||||
|
||||
def save_state(self, state: Dict):
|
||||
"""
|
||||
Save current state to disk.
|
||||
|
||||
Args:
|
||||
state: State dictionary to save. Can contain any JSON-serializable data.
|
||||
|
||||
Example:
|
||||
>>> session.save_state({
|
||||
... 'files_processed': ['a.py', 'b.py'],
|
||||
... 'files_remaining': ['c.py', 'd.py'],
|
||||
... 'operations_completed': 45
|
||||
... })
|
||||
"""
|
||||
data = json.loads(self.session_file.read_text())
|
||||
data["state"] = state
|
||||
data["updated_at"] = datetime.now().isoformat()
|
||||
data["history"].append({
|
||||
"timestamp": datetime.now().isoformat(),
|
||||
"state_snapshot": state
|
||||
})
|
||||
self.session_file.write_text(json.dumps(data, indent=2))
|
||||
|
||||
def load_state(self) -> Dict:
|
||||
"""
|
||||
Load current state from disk.
|
||||
|
||||
Returns:
|
||||
Current state dictionary
|
||||
|
||||
Example:
|
||||
>>> state = session.load_state()
|
||||
>>> print(state.get('files_processed', []))
|
||||
['a.py', 'b.py']
|
||||
"""
|
||||
data = json.loads(self.session_file.read_text())
|
||||
return data.get("state", {})
|
||||
|
||||
def get_history(self) -> List[Dict]:
|
||||
"""
|
||||
Get session history with timestamps.
|
||||
|
||||
Returns:
|
||||
List of historical state snapshots with timestamps
|
||||
|
||||
Example:
|
||||
>>> history = session.get_history()
|
||||
>>> for entry in history:
|
||||
... print(f"{entry['timestamp']}: {entry['state_snapshot']}")
|
||||
"""
|
||||
data = json.loads(self.session_file.read_text())
|
||||
return data.get("history", [])
|
||||
|
||||
def delete(self):
|
||||
"""Delete this session."""
|
||||
if self.session_file.exists():
|
||||
self.session_file.unlink()
|
||||
|
||||
@property
|
||||
def exists(self) -> bool:
|
||||
"""Check if session file exists."""
|
||||
return self.session_file.exists()
|
||||
|
||||
@property
|
||||
def path(self) -> str:
|
||||
"""Get session file path."""
|
||||
return str(self.session_file)
|
||||
|
||||
|
||||
def create_session(name: str, description: str = "") -> Session:
|
||||
"""
|
||||
Create new refactoring session.
|
||||
|
||||
Args:
|
||||
name: Unique session identifier
|
||||
description: Optional description
|
||||
|
||||
Returns:
|
||||
Session object
|
||||
|
||||
Example:
|
||||
>>> session = create_session("rename-api-functions", "Rename all API functions")
|
||||
>>> session.save_state({'progress': 50})
|
||||
"""
|
||||
return Session(name, description)
|
||||
|
||||
|
||||
def load_session(name: str) -> Session:
|
||||
"""
|
||||
Load existing session.
|
||||
|
||||
Args:
|
||||
name: Session identifier
|
||||
|
||||
Returns:
|
||||
Session object
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If session doesn't exist
|
||||
|
||||
Example:
|
||||
>>> session = load_session("rename-api-functions")
|
||||
>>> state = session.load_state()
|
||||
"""
|
||||
session_file = SESSIONS_DIR / f"{name}.json"
|
||||
if not session_file.exists():
|
||||
raise FileNotFoundError(f"Session '{name}' not found")
|
||||
|
||||
return Session(name)
|
||||
|
||||
|
||||
def list_sessions() -> List[str]:
|
||||
"""
|
||||
List all available sessions.
|
||||
|
||||
Returns:
|
||||
List of session names
|
||||
|
||||
Example:
|
||||
>>> sessions = list_sessions()
|
||||
>>> for name in sessions:
|
||||
... print(f"Session: {name}")
|
||||
"""
|
||||
if not SESSIONS_DIR.exists():
|
||||
return []
|
||||
|
||||
return [f.stem for f in SESSIONS_DIR.glob("*.json")]
|
||||
|
||||
|
||||
def delete_session(name: str):
|
||||
"""
|
||||
Delete a session.
|
||||
|
||||
Args:
|
||||
name: Session identifier
|
||||
|
||||
Example:
|
||||
>>> delete_session("old-refactoring-work")
|
||||
"""
|
||||
session = Session(name)
|
||||
session.delete()
|
||||
@@ -0,0 +1,159 @@
|
||||
"""
|
||||
Reusable transformation skills for code execution.
|
||||
|
||||
Skills are Python modules that can be saved and reused across sessions.
|
||||
Useful for common transformations like removing debug statements, adding docstrings, etc.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Optional, List
|
||||
|
||||
|
||||
SKILLS_DIR = Path.home() / ".claude" / "execution-runtime" / "skills"
|
||||
|
||||
|
||||
def save_skill(name: str, code: str, description: Optional[str] = None) -> dict:
|
||||
"""
|
||||
Save reusable skill for future use.
|
||||
|
||||
Skills are saved to ~/.claude/execution-runtime/skills/ and can be
|
||||
imported in future execution sessions.
|
||||
|
||||
Args:
|
||||
name: Skill name (will be used as filename)
|
||||
code: Python code for the skill
|
||||
description: Optional description (added as docstring)
|
||||
|
||||
Returns:
|
||||
Dict with status, path, and import instructions
|
||||
|
||||
Example:
|
||||
>>> save_skill(
|
||||
... name="remove_debug_logs",
|
||||
... code='''
|
||||
... def transform(code):
|
||||
... import re
|
||||
... code = re.sub(r"^\\s*print\\(.*\\)\\n?", "", code, flags=re.MULTILINE)
|
||||
... code = re.sub(r"^\\s*import pdb.*\\n?", "", code, flags=re.MULTILINE)
|
||||
... return code
|
||||
... ''',
|
||||
... description="Remove debug print and pdb statements"
|
||||
... )
|
||||
{'status': 'success', 'skill_name': 'remove_debug_logs', ...}
|
||||
|
||||
# Later, use the skill:
|
||||
>>> import sys
|
||||
>>> sys.path.insert(0, str(SKILLS_DIR))
|
||||
>>> from remove_debug_logs import transform
|
||||
>>> cleaned = transform(original_code)
|
||||
"""
|
||||
SKILLS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
skill_path = SKILLS_DIR / f"{name}.py"
|
||||
|
||||
try:
|
||||
# Add description as docstring if provided
|
||||
if description:
|
||||
header = f'"""{description}"""\n\n'
|
||||
content = header + code
|
||||
else:
|
||||
content = code
|
||||
|
||||
skill_path.write_text(content)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"skill_name": name,
|
||||
"path": str(skill_path),
|
||||
"import_as": f"from skills.{name} import *"
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return {
|
||||
"status": "error",
|
||||
"error": str(e)
|
||||
}
|
||||
|
||||
|
||||
def load_skill(name: str) -> str:
|
||||
"""
|
||||
Load skill code.
|
||||
|
||||
Args:
|
||||
name: Skill name
|
||||
|
||||
Returns:
|
||||
Skill code as string
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If skill doesn't exist
|
||||
|
||||
Example:
|
||||
>>> code = load_skill("remove_debug_logs")
|
||||
>>> print(code[:50])
|
||||
"""Remove debug print and pdb statements"""
|
||||
...
|
||||
"""
|
||||
skill_path = SKILLS_DIR / f"{name}.py"
|
||||
|
||||
if not skill_path.exists():
|
||||
raise FileNotFoundError(
|
||||
f"Skill '{name}' not found. "
|
||||
f"Available skills: {', '.join(list_skills())}"
|
||||
)
|
||||
|
||||
return skill_path.read_text()
|
||||
|
||||
|
||||
def list_skills() -> List[str]:
|
||||
"""
|
||||
List all available skills.
|
||||
|
||||
Returns:
|
||||
List of skill names
|
||||
|
||||
Example:
|
||||
>>> skills = list_skills()
|
||||
>>> for skill in skills:
|
||||
... print(f"Available skill: {skill}")
|
||||
Available skill: remove_debug_logs
|
||||
Available skill: add_docstrings
|
||||
...
|
||||
"""
|
||||
if not SKILLS_DIR.exists():
|
||||
return []
|
||||
|
||||
return [f.stem for f in SKILLS_DIR.glob("*.py") if not f.name.startswith("_")]
|
||||
|
||||
|
||||
def delete_skill(name: str):
|
||||
"""
|
||||
Delete a skill.
|
||||
|
||||
Args:
|
||||
name: Skill name
|
||||
|
||||
Example:
|
||||
>>> delete_skill("old_transformation")
|
||||
"""
|
||||
skill_path = SKILLS_DIR / f"{name}.py"
|
||||
if skill_path.exists():
|
||||
skill_path.unlink()
|
||||
|
||||
|
||||
def get_skill_path() -> Path:
|
||||
"""
|
||||
Get path to skills directory.
|
||||
|
||||
Useful for adding to sys.path to import skills directly.
|
||||
|
||||
Returns:
|
||||
Path to skills directory
|
||||
|
||||
Example:
|
||||
>>> import sys
|
||||
>>> sys.path.insert(0, str(get_skill_path()))
|
||||
>>> from my_skill import transform
|
||||
"""
|
||||
SKILLS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
return SKILLS_DIR
|
||||
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "claude-marketplace-execution-runtime"
|
||||
version = "1.0.0"
|
||||
description = "Code execution environment for Claude Skills Marketplace - implements Anthropic code execution pattern"
|
||||
version = "2.0.0"
|
||||
description = "Code execution environment for Claude Code - implements Anthropic code execution pattern with 90%+ token savings"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
license = {text = "Apache-2.0"}
|
||||
@@ -30,7 +30,7 @@ requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["api", "mcp-server"]
|
||||
packages = ["api", "mcp-server", "execution_runtime"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
|
||||
+64
-118
@@ -1,22 +1,22 @@
|
||||
#!/bin/bash
|
||||
# Automatic MCP setup for Marketplace Execution Runtime
|
||||
# Adds execution runtime to Claude Desktop/Code configuration
|
||||
# Installation script for Claude Code Execution Runtime
|
||||
# Installs Python package for direct imports
|
||||
|
||||
set -e
|
||||
|
||||
echo "🚀 Claude Skills Marketplace - Execution Runtime Setup"
|
||||
echo "======================================================="
|
||||
echo "🚀 Claude Code - Execution Runtime Setup"
|
||||
echo "=========================================="
|
||||
echo ""
|
||||
|
||||
# Detect OS and set config path
|
||||
# Get script directory
|
||||
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
|
||||
# Detect OS
|
||||
if [[ "$OSTYPE" == "darwin"* ]]; then
|
||||
CLAUDE_CONFIG="$HOME/Library/Application Support/Claude/claude_desktop_config.json"
|
||||
OS_NAME="macOS"
|
||||
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
|
||||
CLAUDE_CONFIG="$HOME/.config/Claude/claude_desktop_config.json"
|
||||
OS_NAME="Linux"
|
||||
elif [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "win32" ]]; then
|
||||
CLAUDE_CONFIG="$APPDATA/Claude/claude_desktop_config.json"
|
||||
OS_NAME="Windows"
|
||||
else
|
||||
echo "❌ Unsupported OS: $OSTYPE"
|
||||
@@ -24,128 +24,74 @@ else
|
||||
fi
|
||||
|
||||
echo "📍 Detected OS: $OS_NAME"
|
||||
echo "📁 Config location: $CLAUDE_CONFIG"
|
||||
echo "📁 Installation directory: $SCRIPT_DIR"
|
||||
echo ""
|
||||
|
||||
# Get plugin installation directory
|
||||
PLUGIN_PATH="$HOME/.claude/plugins/marketplaces/mhattingpete-claude-skills/execution-runtime"
|
||||
|
||||
# Check if plugin exists
|
||||
if [ ! -d "$PLUGIN_PATH" ]; then
|
||||
echo "❌ Execution runtime not found at $PLUGIN_PATH"
|
||||
# Check for Python
|
||||
if ! command -v python3 &> /dev/null; then
|
||||
echo "❌ Python 3 not found"
|
||||
echo ""
|
||||
echo "Please install the plugin first:"
|
||||
echo " /plugin marketplace add mhattingpete/claude-skills-marketplace"
|
||||
echo "Please install Python 3.11 or later:"
|
||||
echo " macOS: brew install python@3.11"
|
||||
echo " Linux: apt install python3"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✅ Found execution runtime at: $PLUGIN_PATH"
|
||||
PYTHON_VERSION=$(python3 --version)
|
||||
echo "✅ Found $PYTHON_VERSION"
|
||||
echo ""
|
||||
|
||||
# Check if Claude config exists
|
||||
if [ ! -f "$CLAUDE_CONFIG" ]; then
|
||||
echo "⚠️ Claude config not found"
|
||||
echo "Creating new config file..."
|
||||
mkdir -p "$(dirname "$CLAUDE_CONFIG")"
|
||||
echo '{"mcpServers":{}}' > "$CLAUDE_CONFIG"
|
||||
fi
|
||||
|
||||
# Prompt for allowed directories
|
||||
echo "🔐 Security Configuration"
|
||||
echo "-------------------------"
|
||||
echo "The execution runtime needs permission to access directories."
|
||||
echo "Enter directories to allow (comma-separated), or press Enter for defaults:"
|
||||
echo ""
|
||||
echo "Default: $HOME/Documents, $HOME/Projects"
|
||||
echo ""
|
||||
read -p "Allowed directories: " USER_DIRS
|
||||
|
||||
if [ -z "$USER_DIRS" ]; then
|
||||
ALLOWED_DIRS="$HOME/Documents,$HOME/Projects"
|
||||
else
|
||||
ALLOWED_DIRS="$USER_DIRS"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "Will allow access to: $ALLOWED_DIRS"
|
||||
echo ""
|
||||
|
||||
# Check for uv
|
||||
# Check for pip or uv
|
||||
if command -v uv &> /dev/null; then
|
||||
echo "✅ Found uv package manager"
|
||||
USE_UV=true
|
||||
COMMAND="uv"
|
||||
ARGS='["run", "python", "'$PLUGIN_PATH'/mcp-server/mcp_server.py"]'
|
||||
INSTALLER="uv pip"
|
||||
elif command -v pip3 &> /dev/null; then
|
||||
echo "✅ Found pip"
|
||||
INSTALLER="pip3"
|
||||
else
|
||||
echo "⚠️ uv not found, will use python directly"
|
||||
echo " (Install uv for better performance: curl -LsSf https://astral.sh/uv/install.sh | sh)"
|
||||
USE_UV=false
|
||||
COMMAND="python3"
|
||||
ARGS='["'$PLUGIN_PATH'/mcp-server/mcp_server.py"]'
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "📝 Adding MCP server configuration..."
|
||||
echo ""
|
||||
|
||||
# Update config using Python
|
||||
python3 << EOF
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
config_path = Path("$CLAUDE_CONFIG")
|
||||
config = json.loads(config_path.read_text()) if config_path.exists() else {}
|
||||
|
||||
if 'mcpServers' not in config:
|
||||
config['mcpServers'] = {}
|
||||
|
||||
# Add execution runtime server
|
||||
config['mcpServers']['marketplace-execution'] = {
|
||||
'command': '$COMMAND',
|
||||
'args': $ARGS,
|
||||
'env': {
|
||||
'ALLOWED_DIRECTORIES': '$ALLOWED_DIRS',
|
||||
'MASK_SECRETS': 'true',
|
||||
'AGGRESSIVE_MASKING': 'false'
|
||||
}
|
||||
}
|
||||
|
||||
config_path.write_text(json.dumps(config, indent=2))
|
||||
print("✅ MCP server configured successfully")
|
||||
EOF
|
||||
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "❌ Failed to update config"
|
||||
echo "❌ Neither pip nor uv found"
|
||||
echo ""
|
||||
echo "Please install pip or uv first"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Install dependencies if using uv
|
||||
if [ "$USE_UV" = true ]; then
|
||||
echo ""
|
||||
echo "📦 Installing dependencies..."
|
||||
cd "$PLUGIN_PATH"
|
||||
uv pip install -e . > /dev/null 2>&1 || true
|
||||
echo "✅ Dependencies installed"
|
||||
fi
|
||||
echo ""
|
||||
echo "📦 Installing execution-runtime package..."
|
||||
echo ""
|
||||
|
||||
echo ""
|
||||
echo "✨ Setup Complete!"
|
||||
echo "=================="
|
||||
echo ""
|
||||
echo "Next steps:"
|
||||
echo " 1. Restart Claude Code or Claude Desktop"
|
||||
echo " 2. The execution runtime will be available automatically"
|
||||
echo ""
|
||||
echo "📊 Benefits you now have:"
|
||||
echo " ✓ 90%+ token savings for bulk operations"
|
||||
echo " ✓ Local code execution with API imports"
|
||||
echo " ✓ Stateful multi-step refactoring"
|
||||
echo " ✓ Automatic secret/PII masking"
|
||||
echo ""
|
||||
echo "📖 Documentation:"
|
||||
echo " $PLUGIN_PATH/README.md"
|
||||
echo ""
|
||||
echo "🧪 Test the installation:"
|
||||
echo " Ask Claude: 'Can you execute Python code using the marketplace API?'"
|
||||
echo ""
|
||||
echo "Happy coding! 🚀"
|
||||
cd "$SCRIPT_DIR"
|
||||
|
||||
# Install package in editable mode
|
||||
$INSTALLER install -e .
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
echo ""
|
||||
echo "✨ Installation Complete!"
|
||||
echo "========================"
|
||||
echo ""
|
||||
echo "The execution runtime is now available for direct import:"
|
||||
echo ""
|
||||
echo " from execution_runtime import fs, code, transform, git"
|
||||
echo ""
|
||||
echo "Example usage:"
|
||||
echo " # Find functions (metadata only)"
|
||||
echo " functions = code.find_functions('app.py')"
|
||||
echo ""
|
||||
echo " # Rename across codebase"
|
||||
echo " result = transform.rename_identifier('.', 'old', 'new', '**/*.py')"
|
||||
echo ""
|
||||
echo " # Copy lines between files"
|
||||
echo " code_block = fs.copy_lines('source.py', 10, 20)"
|
||||
echo ""
|
||||
echo "📖 Documentation: $SCRIPT_DIR/README.md"
|
||||
echo ""
|
||||
echo "Happy coding! 🚀"
|
||||
else
|
||||
echo ""
|
||||
echo "❌ Installation failed"
|
||||
echo ""
|
||||
echo "Try manually:"
|
||||
echo " cd $SCRIPT_DIR"
|
||||
echo " pip3 install -e ."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
Reference in New Issue
Block a user