Format Document
curl --request POST \
--url https://api.example.com/tools/format_documentimport requests
url = "https://api.example.com/tools/format_document"
response = requests.post(url)
print(response.text)const options = {method: 'POST'};
fetch('https://api.example.com/tools/format_document', 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/format_document",
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/format_document"
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/format_document")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.example.com/tools/format_document")
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{
"edits": [
{
"range": {
"start": {},
"end": {}
},
"newText": "<string>"
}
],
"totalEdits": 123
}API Reference
Format Document
Automatically format Python code to match style guidelines
POST
/
tools
/
format_document
Format Document
curl --request POST \
--url https://api.example.com/tools/format_documentimport requests
url = "https://api.example.com/tools/format_document"
response = requests.post(url)
print(response.text)const options = {method: 'POST'};
fetch('https://api.example.com/tools/format_document', 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/format_document",
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/format_document"
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/format_document")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.example.com/tools/format_document")
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{
"edits": [
{
"range": {
"start": {},
"end": {}
},
"newText": "<string>"
}
],
"totalEdits": 123
}Overview
Automatically format your Python code according to PEP 8 style guidelines. This tool provides the same formatting you get from tools like Black, autopep8, or yapf.Request
string
required
File URI (e.g.,
file:///workspace/main.py)object
Response
array
number
Number of changes made
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": "format_document",
"arguments": {
"uri": "file:///workspace/app/utils.py",
"options": {
"tabSize": 4,
"insertSpaces": true,
"lineLength": 88
}
}
}'
from pylance_mcp import Client
client = Client(api_key="YOUR_API_KEY")
formatted = client.format_document(
uri="file:///workspace/app/utils.py",
options={
"tab_size": 4,
"insert_spaces": True,
"line_length": 88
}
)
print(f"Made {formatted.total_edits} formatting changes")
# Apply the edits
for edit in formatted.edits:
print(f"Line {edit.range.start.line}: Formatting update")
import { PylanceMCP } from '@pylance-mcp/client';
const client = new PylanceMCP({ apiKey: 'YOUR_API_KEY' });
const formatted = await client.formatDocument({
uri: 'file:///workspace/app/utils.py',
options: {
tabSize: 4,
insertSpaces: true,
lineLength: 88
}
});
console.log(`Made ${formatted.totalEdits} formatting changes`);
import { PylanceMCP, FormatDocumentRequest } from '@pylance-mcp/client';
const client = new PylanceMCP({ apiKey: process.env.PYLANCE_API_KEY! });
const request: FormatDocumentRequest = {
uri: 'file:///workspace/app/utils.py',
options: {
tabSize: 4,
insertSpaces: true,
lineLength: 88
}
};
const formatted = await client.formatDocument(request);
console.log(`Made ${formatted.totalEdits} formatting changes`);
Example Response
{
"edits": [
{
"range": {
"start": { "line": 5, "character": 0 },
"end": { "line": 5, "character": 47 }
},
"newText": "def calculate_total(items: List[Item], tax_rate: float = 0.1) -> float:"
},
{
"range": {
"start": { "line": 8, "character": 8 },
"end": { "line": 8, "character": 65 }
},
"newText": " return sum(item.price for item in items) * (1 + tax_rate)"
}
],
"totalEdits": 2
}
What Gets Formatted
Indentation
Consistent spaces/tabs and nesting levels
Line Length
Wraps long lines to stay under limit
Spacing
Proper spacing around operators and commas
Imports
Organizes and sorts import statements
Formatting Examples
Before and After
def calculate_total(items,tax_rate=0.1,discount=0)->float:
subtotal=sum([item.price for item in items])
tax=subtotal*tax_rate
return subtotal+tax-discount
class User:
def __init__(self,name,email):
self.name=name
self.email=email
def calculate_total(
items: List[Item], tax_rate: float = 0.1, discount: float = 0
) -> float:
subtotal = sum([item.price for item in items])
tax = subtotal * tax_rate
return subtotal + tax - discount
class User:
def __init__(self, name: str, email: str):
self.name = name
self.email = email
Import Organization
import os
from typing import List
import sys
from app.models import User
import json
from app.utils import calculate
import json
import os
import sys
from typing import List
from app.models import User
from app.utils import calculate
Line Wrapping
result = some_function(first_parameter, second_parameter, third_parameter, fourth_parameter, fifth_parameter)
result = some_function(
first_parameter,
second_parameter,
third_parameter,
fourth_parameter,
fifth_parameter,
)
Formatting Styles
Choose your preferred line length:| Style | Line Length | Description |
|---|---|---|
| Black | 88 | Modern, opinionated formatter |
| PEP 8 | 79 | Traditional Python standard |
| 80 | Google Python Style Guide | |
| Custom | Any | Your preferred maximum |
Use Cases
Format on Save
# Auto-format every time you save a file
def on_file_save(file_uri):
formatted = client.format_document(uri=file_uri)
if formatted.total_edits > 0:
apply_edits(file_uri, formatted.edits)
print(f"✨ Formatted {file_uri}")
Pre-Commit Hook
# Format all changed files before committing
def format_changed_files():
changed_files = get_git_changed_files()
python_files = [f for f in changed_files if f.endswith('.py')]
for file in python_files:
formatted = client.format_document(uri=file)
if formatted.total_edits > 0:
apply_edits(file, formatted.edits)
print(f"📝 Formatted {file}")
return len(python_files)
Code Review Automation
# Check if code follows formatting standards
def check_formatting_compliance(file_uri):
formatted = client.format_document(uri=file_uri)
if formatted.total_edits == 0:
return {"compliant": True, "message": "✅ Code is properly formatted"}
else:
return {
"compliant": False,
"message": f"❌ {formatted.total_edits} formatting issues found",
"fixes": formatted.edits
}
Configuration Options
Tab Size
# Use 2-space indentation (not recommended for Python)
formatted = client.format_document(
uri=file_uri,
options={"tab_size": 2}
)
# Standard 4-space indentation
formatted = client.format_document(
uri=file_uri,
options={"tab_size": 4}
)
Line Length
# Strict PEP 8 (79 characters)
formatted = client.format_document(
uri=file_uri,
options={"line_length": 79}
)
# Black style (88 characters)
formatted = client.format_document(
uri=file_uri,
options={"line_length": 88}
)
# More permissive (120 characters)
formatted = client.format_document(
uri=file_uri,
options={"line_length": 120}
)
Performance Tips
Format on Demand: Don’t format constantly - only on save or commit
Cache Results: If file hasn’t changed, formatting result is the same
Batch Format: Format multiple files in sequence, not parallel
Error Responses
| Code | Reason | Solution |
|---|---|---|
FILE_NOT_FOUND | File doesn’t exist | Verify file path |
PARSE_ERROR | File has syntax errors | Fix syntax errors first |
INVALID_OPTIONS | Formatting options invalid | Check option values |
FILE_TOO_LARGE | File exceeds size limit | Split into smaller files |
Rate Limits
| Tier | Requests/Hour | Requests/Day | Max File Size |
|---|---|---|---|
| Free | 20 | 100 | 100KB |
| Hobby | 500 | 5,000 | 500KB |
| Pro | 5,000 | 50,000 | 1MB |
| Enterprise | Unlimited | Unlimited | 10MB |
Best Practices
Team Consistency: Use the same line length across your team
Version Control: Configure formatting before committing to avoid large diffs
IDE Integration: Set up format-on-save in your editor
CI/CD: Add formatting checks to your build pipeline
Related Tools
Get Diagnostics
Check for style violations
Apply Workspace Edit
Apply formatting changes
Get Code Actions
Get quick fixes for issues
Rename Symbol
Refactor code safely
Was this page helpful?
⌘I