Skip to main content
POST
/
tools
/
format_document
Format Document
curl --request POST \
  --url https://api.example.com/tools/format_document
{
  "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

uri
string
required
File URI (e.g., file:///workspace/main.py)
options
object
Formatting options

Response

edits
array
Array of text edits to apply
totalEdits
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
      }
    }
  }'

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

Import Organization

import os
from typing import List
import sys
from app.models import User
import json
from app.utils import calculate

Line Wrapping

result = some_function(first_parameter, second_parameter, third_parameter, fourth_parameter, fifth_parameter)

Formatting Styles

Choose your preferred line length:
StyleLine LengthDescription
Black88Modern, opinionated formatter
PEP 879Traditional Python standard
Google80Google Python Style Guide
CustomAnyYour 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

CodeReasonSolution
FILE_NOT_FOUNDFile doesn’t existVerify file path
PARSE_ERRORFile has syntax errorsFix syntax errors first
INVALID_OPTIONSFormatting options invalidCheck option values
FILE_TOO_LARGEFile exceeds size limitSplit into smaller files

Rate Limits

TierRequests/HourRequests/DayMax File Size
Free20100100KB
Hobby5005,000500KB
Pro5,00050,0001MB
EnterpriseUnlimitedUnlimited10MB

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