update_symbolΒΆ
Safely replace a function, class, or method in a source file with new code while preserving surrounding code and creating backups.
Quick ReferenceΒΆ
update_symbol(
file_path: str, # Path to file
target_type: str, # "function", "class", "method"
target_name: str, # Symbol name
new_code: str, # New implementation
create_backup: bool = True, # Create .bak file
operation: str = "replace" # "replace" or "delete"
) -> UpdateResult
User StoriesΒΆ
| Persona | Story | Tool Value |
|---|---|---|
| π€ Sarah (AI User) | "Safely update AI-generated code with automatic backups" | Safe code changes |
| π₯ David (Team Lead) | "Update functions without breaking surrounding code" | Surgical modifications |
| π§ Chris (OSS Contributor) | "Contribute code changes with confidence" | Safe contributions |
ParametersΒΆ
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
file_path | string | Yes | - | Absolute path to file |
target_type | string | Yes | - | "function", "class", or "method" |
target_name | string | Yes | - | Name of symbol to update |
new_code | string | Yes* | - | New code (required unless operation="delete") |
create_backup | bool | No | true | Create backup before modifying |
operation | string | No | "replace" | "replace" or "delete" |
Response SchemaΒΆ
{
"data": {
"file_path": "string",
"target_name": "string",
"target_type": "string",
"status": "string",
"backup_path": "string | null",
"lines_changed": {
"before": ["integer", "integer"],
"after": ["integer", "integer"]
},
"diff": "string"
},
"error": null,
"tier_applied": "string",
"duration_ms": "integer"
}
ExamplesΒΆ
Replace a FunctionΒΆ
{
"file_path": "/project/src/validators.py",
"target_type": "function",
"target_name": "validate_email",
"new_code": "def validate_email(email: str) -> bool:\n \"\"\"Validate email format using RFC 5322 pattern.\"\"\"\n import re\n pattern = r\"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$\"\n return bool(re.match(pattern, email))"
}
{
"data": {
"file_path": "/project/src/validators.py",
"target_name": "validate_email",
"target_type": "function",
"status": "updated",
"backup_path": "/project/src/validators.py.bak",
"lines_changed": {
"before": [15, 19],
"after": [15, 20]
},
"diff": "--- before\n+++ after\n@@ -15,5 +15,6 @@\n-def validate_email(email: str) -> bool:\n- \"\"\"Validate email format.\"\"\"\n- pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$'\n- return bool(re.match(pattern, email))\n+def validate_email(email: str) -> bool:\n+ \"\"\"Validate email format using RFC 5322 pattern.\"\"\"\n+ import re\n+ pattern = r\"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@...\"\n+ return bool(re.match(pattern, email))"
},
"tier_applied": "community",
"duration_ms": 45
}
Replace a MethodΒΆ
{
"file_path": "/project/processor.py",
"target_type": "method",
"target_name": "DataProcessor.process",
"new_code": "def process(self, data: list) -> list:\n \"\"\"Process data items with error handling.\"\"\"\n results = []\n for item in data:\n try:\n transformed = self.transform(item)\n validated = self.validate(transformed)\n results.append(validated)\n except ProcessingError as e:\n self.logger.error(f\"Failed to process item: {e}\")\n continue\n return results"
}
Replace a ClassΒΆ
{
"file_path": "/project/config.py",
"target_type": "class",
"target_name": "Config",
"new_code": "@dataclass\nclass Config:\n \"\"\"Application configuration.\"\"\"\n database_url: str\n debug: bool = False\n log_level: str = \"INFO\"\n max_connections: int = 10\n \n @classmethod\n def from_env(cls) -> 'Config':\n return cls(\n database_url=os.environ['DATABASE_URL'],\n debug=os.environ.get('DEBUG', 'false').lower() == 'true',\n log_level=os.environ.get('LOG_LEVEL', 'INFO'),\n max_connections=int(os.environ.get('MAX_CONNECTIONS', '10'))\n )"
}
Delete a FunctionΒΆ
Update Without BackupΒΆ
Tier DifferencesΒΆ
This tool is available at all tiers. What differs are the limits and capabilities:
| Feature | Community | Pro | Enterprise |
|---|---|---|---|
| Availability | β Available | β Available | β Available |
| Basic updates | β | β | β |
| Backup creation | β | β | β |
| Diff generation | β | β | β |
| Protected files | Not available | β οΈ Warning | π‘οΈ Enforced |
| Audit logging | Not available | β | β |
| Approval workflow | Not available | Not available | β |
Error HandlingΒΆ
Symbol Not FoundΒΆ
{
"data": null,
"error": {
"code": "SYMBOL_NOT_FOUND",
"message": "Function 'validat_email' not found in validators.py",
"suggestions": ["validate_email", "validate_phone"],
"available_symbols": {
"functions": ["validate_email", "validate_phone", "validate_url"]
}
}
}
Syntax Error in New CodeΒΆ
{
"data": null,
"error": {
"code": "SYNTAX_ERROR",
"message": "New code has syntax error at line 3: unexpected indent",
"details": {
"line": 3,
"column": 4,
"context": " return bool(re.match(pattern, email)"
}
}
}
Protected File (Enterprise)ΒΆ
{
"data": null,
"error": {
"code": "PROTECTED_FILE",
"message": "File 'src/security/auth.py' is protected",
"policy": "Modifications require approval from security-team",
"approvers": ["security-team"]
}
}
Tier LimitsΒΆ
update_symbol capabilities vary by tier:
| Feature | Community | Pro | Enterprise |
|---|---|---|---|
| Backup enabled | β | β | β |
| Validation level | Syntax | Semantic | Full |
| Max updates per call | 10 | Unlimited | Unlimited |
| Single file update | β | β | β |
| Cross-file import updates | β | β | β |
| Semantic validation | β | β | β |
| Type checking | β | β | β Full |
| Protected files | β | β | β Policy-based |
Community TierΒΆ
- β Safely replace functions, classes, methods
- β Automatic backup creation (.bak files)
- β Syntax validation before updating
- β Preserve surrounding code
- β οΈ Max 10 updates per call - Small refactorings only
- β οΈ Syntax-only validation - May introduce semantic errors
- β No cross-file import updates
- β No type checking
Pro TierΒΆ
- β All Community features
- β Unlimited updates per call - Large refactorings
- β Semantic validation - Ensure code makes sense
- β Cross-file import updates - Update imports automatically
- β Type checking - Verify types are correct
- β Reference tracking - See what calls the symbol
Enterprise TierΒΆ
- β All Pro features
- β Full validation - Complete correctness checks
- β Protected files - Policy-based write protection
- β Approval workflows - Require team approval
- β Audit trail - Track all symbol changes
- β Rollback support - Multi-level undo
Key Difference: Validation Depth and Safety - Community: Syntax validation, 10 updates - Basic safety - Pro: Semantic validation, unlimited - Production refactoring - Enterprise: Full validation, protected files - Enterprise safety
Best PracticesΒΆ
- Extract before updating - Always get current code first
- Keep backups enabled - Easy rollback if needed
- Test new code separately - Verify syntax before updating
- Use simulate_refactor - Verify behavior preservation
Recommended WorkflowΒΆ
graph TD
A[extract_code] --> B[Modify locally]
B --> C[simulate_refactor]
C -->|Safe| D[update_symbol]
C -->|Unsafe| E[Revise changes]
E --> B
D --> F[Verify file] Related ToolsΒΆ
- extract_code - Get code before updating
- rename_symbol - Rename instead of replace
- simulate_refactor - Test changes safely