Apply Workspace Edit
curl --request POST \
--url https://api.example.com/tools/apply_workspace_editimport requests
url = "https://api.example.com/tools/apply_workspace_edit"
response = requests.post(url)
print(response.text)const options = {method: 'POST'};
fetch('https://api.example.com/tools/apply_workspace_edit', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.example.com/tools/apply_workspace_edit",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"net/http"
"io"
)
func main() {
url := "https://api.example.com/tools/apply_workspace_edit"
req, _ := http.NewRequest("POST", url, nil)
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.example.com/tools/apply_workspace_edit")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.example.com/tools/apply_workspace_edit")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
response = http.request(request)
puts response.read_body{
"applied": true,
"failureReason": "<string>",
"filesModified": 123,
"totalEdits": 123
}API Reference
Apply Workspace Edit
Apply text edits to files in your workspace
POST
/
tools
/
apply_workspace_edit
Apply Workspace Edit
curl --request POST \
--url https://api.example.com/tools/apply_workspace_editimport requests
url = "https://api.example.com/tools/apply_workspace_edit"
response = requests.post(url)
print(response.text)const options = {method: 'POST'};
fetch('https://api.example.com/tools/apply_workspace_edit', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.example.com/tools/apply_workspace_edit",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"net/http"
"io"
)
func main() {
url := "https://api.example.com/tools/apply_workspace_edit"
req, _ := http.NewRequest("POST", url, nil)
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.example.com/tools/apply_workspace_edit")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.example.com/tools/apply_workspace_edit")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
response = http.request(request)
puts response.read_body{
"applied": true,
"failureReason": "<string>",
"filesModified": 123,
"totalEdits": 123
}Overview
Apply text changes to one or more files in your workspace. This is used to execute the edits returned by other tools like rename, format, or code actions.Request
object
required
string
Optional description of the edit (e.g., “Rename variable”)
Response
boolean
Whether the edit was successfully applied
string
Error message if
applied is falsenumber
Number of files that were changed
number
Total number of text edits applied
Example Request
curl -X POST https://api.pylancemcp.dev/v1/tools/call \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "apply_workspace_edit",
"arguments": {
"edit": {
"changes": {
"file:///workspace/app/utils.py": [
{
"range": {
"start": {"line": 8, "character": 4},
"end": {"line": 8, "character": 19}
},
"newText": "compute_total"
}
]
}
},
"label": "Rename function"
}
}'
from pylance_mcp import Client
client = Client(api_key="YOUR_API_KEY")
# Get edits from another operation (e.g., rename)
rename_result = client.rename_symbol(...)
# Apply the edits
result = client.apply_workspace_edit(
edit=rename_result.changes,
label="Rename calculate_total to compute_total"
)
if result.applied:
print(f"✅ Modified {result.files_modified} files")
print(f" Applied {result.total_edits} edits")
else:
print(f"❌ Failed: {result.failure_reason}")
import { PylanceMCP } from '@pylance-mcp/client';
const client = new PylanceMCP({ apiKey: 'YOUR_API_KEY' });
// Get edits from another operation
const renameResult = await client.renameSymbol(...);
// Apply the edits
const result = await client.applyWorkspaceEdit({
edit: renameResult.changes,
label: 'Rename calculate_total to compute_total'
});
if (result.applied) {
console.log(`✅ Modified ${result.filesModified} files`);
console.log(` Applied ${result.totalEdits} edits`);
} else {
console.log(`❌ Failed: ${result.failureReason}`);
}
import { PylanceMCP, WorkspaceEditRequest } from '@pylance-mcp/client';
const client = new PylanceMCP({ apiKey: process.env.PYLANCE_API_KEY! });
// Get edits from another operation
const renameResult = await client.renameSymbol(...);
// Apply the edits
const request: WorkspaceEditRequest = {
edit: renameResult.changes,
label: 'Rename calculate_total to compute_total'
};
const result = await client.applyWorkspaceEdit(request);
if (result.applied) {
console.log(`✅ Modified ${result.filesModified} files`);
console.log(` Applied ${result.totalEdits} edits`);
} else {
console.log(`❌ Failed: ${result.failureReason}`);
}
Example Response
{
"applied": true,
"filesModified": 3,
"totalEdits": 12
}
Use Cases
Apply Rename Edits
# 1. Get rename edits
rename = client.rename_symbol(
uri="file:///workspace/app/utils.py",
line=8,
character=4,
new_name="compute_total"
)
# 2. Apply the edits
result = client.apply_workspace_edit(
edit=rename.changes,
label="Rename calculate_total to compute_total"
)
if result.applied:
print(f"✅ Renamed across {result.files_modified} files")
Apply Format Changes
# 1. Get format edits
formatted = client.format_document(
uri="file:///workspace/app/views.py"
)
# 2. Convert to workspace edit format
workspace_edit = {
"file:///workspace/app/views.py": formatted.edits
}
# 3. Apply the formatting
result = client.apply_workspace_edit(
edit=workspace_edit,
label="Format document"
)
Apply Code Action
# 1. Get code actions
actions = client.get_code_actions(uri=file_uri, range=error_range)
# 2. Find the quickfix to apply
quickfix = next(a for a in actions.actions if a.kind == "quickfix")
# 3. Apply it
result = client.apply_workspace_edit(
edit=quickfix.edit,
label=quickfix.title
)
if result.applied:
print(f"✅ Applied fix: {quickfix.title}")
Batch Multiple Edits
# Apply edits to multiple files at once
workspace_edit = {
"file:///workspace/app/utils.py": [
{"range": {...}, "newText": "new_name"}
],
"file:///workspace/app/views.py": [
{"range": {...}, "newText": "new_name"},
{"range": {...}, "newText": "import new_name"}
],
"file:///workspace/tests/test_utils.py": [
{"range": {...}, "newText": "new_name"}
]
}
result = client.apply_workspace_edit(
edit=workspace_edit,
label="Update references"
)
Edit Application Order
Edits are applied in a specific order to prevent conflicts:1
Sort by File
Group edits by file URI
2
Sort by Position
Within each file, sort edits from bottom to top (descending line/character)
3
Apply Edits
Apply each edit, preventing line number shifts
4
Verify
Confirm all edits applied successfully
Bottom-to-top ordering ensures that edits don’t affect the positions of subsequent edits.
Error Handling
The operation is atomic - either all edits succeed or none are applied:result = client.apply_workspace_edit(edit=workspace_edit)
if not result.applied:
if "FILE_NOT_FOUND" in result.failure_reason:
print("❌ One or more files don't exist")
elif "PERMISSION_DENIED" in result.failure_reason:
print("❌ Cannot write to files")
elif "CONFLICTING_EDITS" in result.failure_reason:
print("❌ Edits overlap - cannot apply safely")
else:
print(f"❌ Failed: {result.failure_reason}")
Safety Features
Atomic Operation
All files updated together or none at all
Conflict Detection
Overlapping edits are rejected
Validation
File paths and ranges validated before applying
Rollback Support
Failed edits don’t leave partial changes
Best Practices
Preview First: Show user what will change before applying
Use Version Control: Commit before large edits so you can revert
Validate Ranges: Ensure all ranges are valid before applying
Add Labels: Always provide descriptive labels for better UX
Performance Tips
Batch Edits: Apply multiple files in one operation instead of separate calls
Non-Overlapping: Ensure edits don’t overlap for faster application
Minimize Scope: Only edit necessary files and ranges
Error Responses
| Code | Reason | Solution |
|---|---|---|
FILE_NOT_FOUND | One or more files don’t exist | Verify all file URIs |
PERMISSION_DENIED | Cannot write to file | Check file permissions |
INVALID_RANGE | Range out of bounds | Validate line/character positions |
CONFLICTING_EDITS | Overlapping edits in same file | Resolve conflicts first |
FILE_MODIFIED | File changed since edits were generated | Regenerate edits |
READONLY_FILE | File is read-only | Remove read-only flag |
Rollback
If you need to undo an edit:# Save original content before applying
original_content = {}
for file_uri in workspace_edit.keys():
with open(file_uri.replace('file://', ''), 'r') as f:
original_content[file_uri] = f.read()
# Apply edit
result = client.apply_workspace_edit(edit=workspace_edit)
# If something went wrong, restore original
if not result.applied or user_wants_undo:
for file_uri, content in original_content.items():
with open(file_uri.replace('file://', ''), 'w') as f:
f.write(content)
Rate Limits
| Tier | Requests/Hour | Requests/Day | Max Files/Edit | Max Edits/File |
|---|---|---|---|---|
| Free | 10 | 50 | 5 | 100 |
| Hobby | 250 | 2,500 | 20 | 500 |
| Pro | 2,500 | 25,000 | 100 | 5,000 |
| Enterprise | Unlimited | Unlimited | Unlimited | Unlimited |
Large workspace edits count as one request but may take longer to apply.
Related Tools
Rename Symbol
Generate rename edits to apply
Format Document
Generate format edits to apply
Get Code Actions
Get quick fix edits to apply
Get Diagnostics
Verify no errors after applying
Was this page helpful?