Read File
curl --request GET \
--url https://api.example.com/resources/file/{path}import requests
url = "https://api.example.com/resources/file/{path}"
response = requests.get(url)
print(response.text)const options = {method: 'GET'};
fetch('https://api.example.com/resources/file/{path}', 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/resources/file/{path}",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
]);
$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/resources/file/{path}"
req, _ := http.NewRequest("GET", url, nil)
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.get("https://api.example.com/resources/file/{path}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.example.com/resources/file/{path}")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Get.new(url)
response = http.request(request)
puts response.read_body{
"error": {
"code": "FILE_NOT_FOUND",
"message": "File does not exist",
"details": {
"path": "/workspace/src/missing.py",
"workspaceRoot": "/workspace"
}
}
}
{
"error": {
"code": "PERMISSION_DENIED",
"message": "Cannot read file outside workspace",
"details": {
"path": "/etc/passwd",
"reason": "Path traversal attempt"
}
}
}
{
"error": {
"code": "ENCODING_ERROR",
"message": "Failed to decode file",
"details": {
"path": "/workspace/src/binary.py",
"requestedEncoding": "utf-8",
"detectedEncoding": "binary"
}
}
}
{
"error": {
"code": "FILE_TOO_LARGE",
"message": "File exceeds size limit",
"details": {
"size": 52428800,
"limit": 10485760,
"suggestion": "Use lineRange parameter to read in chunks"
}
}
}
API Reference
Read File
Read the contents of a specific file in the workspace
GET
/
resources
/
file
/
{path}
Read File
curl --request GET \
--url https://api.example.com/resources/file/{path}import requests
url = "https://api.example.com/resources/file/{path}"
response = requests.get(url)
print(response.text)const options = {method: 'GET'};
fetch('https://api.example.com/resources/file/{path}', 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/resources/file/{path}",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
]);
$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/resources/file/{path}"
req, _ := http.NewRequest("GET", url, nil)
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.get("https://api.example.com/resources/file/{path}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.example.com/resources/file/{path}")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Get.new(url)
response = http.request(request)
puts response.read_body{
"error": {
"code": "FILE_NOT_FOUND",
"message": "File does not exist",
"details": {
"path": "/workspace/src/missing.py",
"workspaceRoot": "/workspace"
}
}
}
{
"error": {
"code": "PERMISSION_DENIED",
"message": "Cannot read file outside workspace",
"details": {
"path": "/etc/passwd",
"reason": "Path traversal attempt"
}
}
}
{
"error": {
"code": "ENCODING_ERROR",
"message": "Failed to decode file",
"details": {
"path": "/workspace/src/binary.py",
"requestedEncoding": "utf-8",
"detectedEncoding": "binary"
}
}
}
{
"error": {
"code": "FILE_TOO_LARGE",
"message": "File exceeds size limit",
"details": {
"size": 52428800,
"limit": 10485760,
"suggestion": "Use lineRange parameter to read in chunks"
}
}
}
Overview
Theread-file resource returns the full contents of a specific file in your workspace, along with metadata and encoding information.
Resource URI
pylance://file/{path}
Request
string
required
Resource URI with file path:
pylance://file/src/main.pystring
default:"utf-8"
Character encoding (
utf-8, ascii, latin-1, utf-16)boolean
default:"true"
Include file metadata in response
object
Optional line range to read (e.g.,
{"start": 10, "end": 50})Response
string
Full file contents as string
string
Absolute file path
string
Path relative to workspace root
object
Example Request
curl -X POST https://api.pylancemcp.dev/v1/resources/read \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"uri": "pylance://file/src/models/user.py",
"params": {
"encoding": "utf-8",
"includeMetadata": true
}
}'
from pylance_mcp import MCPClient
client = MCPClient(api_key="YOUR_API_KEY")
file = client.read_resource(
uri="pylance://file/src/models/user.py",
encoding="utf-8",
includeMetadata=True
)
print(file["content"])
print(f"Lines: {file['metadata']['lines']}")
print(f"Size: {file['metadata']['size']} bytes")
const { MCPClient } = require('@pylancemcp/client');
const client = new MCPClient({ apiKey: 'YOUR_API_KEY' });
const file = await client.readResource({
uri: 'pylance://file/src/models/user.py',
params: {
encoding: 'utf-8',
includeMetadata: true
}
});
console.log(file.content);
console.log(`Lines: ${file.metadata.lines}`);
import { MCPClient, FileResource } from '@pylancemcp/client';
const client = new MCPClient({ apiKey: 'YOUR_API_KEY' });
const file: FileResource = await client.readResource({
uri: 'pylance://file/src/models/user.py',
params: {
encoding: 'utf-8',
includeMetadata: true
}
});
console.log(file.content);
console.log(`Lines: ${file.metadata.lines}`);
Example Response
{
"content": "from typing import Optional\nfrom datetime import datetime\n\nclass User:\n \"\"\"User model representing a system user.\"\"\"\n \n def __init__(self, email: str, name: str):\n self.email = email\n self.name = name\n self.created_at = datetime.now()\n \n def __repr__(self) -> str:\n return f\"<User(email='{self.email}')>\"",
"path": "/workspace/src/models/user.py",
"relativePath": "src/models/user.py",
"metadata": {
"size": 342,
"lines": 13,
"encoding": "utf-8",
"language": "python",
"lastModified": "2025-12-16T15:20:00Z",
"hash": "a3f5e8c9d2b1f4e7a6c8d9e2f1b3a4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1"
}
}
Reading Line Ranges
Read specific line ranges for large files:# Read lines 50-100
file = client.read_resource(
uri="pylance://file/src/large_file.py",
lineRange={"start": 50, "end": 100}
)
print(file["content"]) # Only lines 50-100
print(f"Lines returned: {file['metadata']['linesReturned']}")
{
"content": "# Lines 50-100 of the file...",
"metadata": {
"linesReturned": 51,
"totalLines": 5000,
"lineRange": {"start": 50, "end": 100}
}
}
Character Encodings
Supported encodings:| Encoding | Description | Use Case |
|---|---|---|
utf-8 | Unicode (default) | Modern Python files |
ascii | ASCII only | Legacy files |
latin-1 | ISO-8859-1 | Western European |
utf-16 | Unicode 16-bit | Windows files |
cp1252 | Windows-1252 | Windows legacy |
Pylance automatically detects encoding from BOM (Byte Order Mark) and file headers. Specify encoding only if detection fails.
Common Use Cases
Read Complete File
file = client.read_resource(uri="pylance://file/src/main.py")
content = file["content"]
Read Large File in Chunks
chunk_size = 100
total_lines = 5000
for start in range(0, total_lines, chunk_size):
chunk = client.read_resource(
uri="pylance://file/src/large_file.py",
lineRange={"start": start, "end": start + chunk_size}
)
process_chunk(chunk["content"])
Get File Hash for Caching
file = client.read_resource(
uri="pylance://file/src/models/user.py",
includeMetadata=True
)
cache_key = file["metadata"]["hash"]
if cache_key in cache:
content = cache[cache_key]
else:
content = file["content"]
cache[cache_key] = content
Performance Considerations
Files larger than 10MB will be automatically chunked. Use
lineRange to read specific sections.Optimization Tips
Cache file contents using the SHA-256 hash
Use line ranges for large files (>1000 lines)
Disable metadata if not needed to reduce response size
Batch multiple file reads in parallel
import asyncio
async def read_multiple_files(files):
tasks = [
client.read_resource_async(uri=f"pylance://file/{file}")
for file in files
]
return await asyncio.gather(*tasks)
files = ["src/main.py", "src/utils.py", "src/models.py"]
results = asyncio.run(read_multiple_files(files))
Error Responses
{
"error": {
"code": "FILE_NOT_FOUND",
"message": "File does not exist",
"details": {
"path": "/workspace/src/missing.py",
"workspaceRoot": "/workspace"
}
}
}
{
"error": {
"code": "PERMISSION_DENIED",
"message": "Cannot read file outside workspace",
"details": {
"path": "/etc/passwd",
"reason": "Path traversal attempt"
}
}
}
{
"error": {
"code": "ENCODING_ERROR",
"message": "Failed to decode file",
"details": {
"path": "/workspace/src/binary.py",
"requestedEncoding": "utf-8",
"detectedEncoding": "binary"
}
}
}
{
"error": {
"code": "FILE_TOO_LARGE",
"message": "File exceeds size limit",
"details": {
"size": 52428800,
"limit": 10485760,
"suggestion": "Use lineRange parameter to read in chunks"
}
}
}
Security
Path Traversal Prevention
All paths are validated to prevent directory traversal attacks. Attempts to access files outside the workspace will be rejected.
# ❌ These will fail with PERMISSION_DENIED
client.read_resource(uri="pylance://file/../../../etc/passwd")
client.read_resource(uri="pylance://file//etc/hosts")
client.read_resource(uri="pylance://file/~/private_data.txt")
# ✅ These will work (within workspace)
client.read_resource(uri="pylance://file/src/main.py")
client.read_resource(uri="pylance://file/src/../utils/helpers.py") # Resolves to src/utils/helpers.py
client.read_resource(uri="pylance://file/./src/main.py") # Resolves to src/main.py
Rate Limits
| Tier | Requests/Day | Max File Size |
|---|---|---|
| Free | 100 | 1 MB |
| Hobby | 5,000 | 5 MB |
| Pro | 50,000 | 10 MB |
| Enterprise | Unlimited | 50 MB |
Related Resources
List Files
Get all files in workspace
Workspace Structure
View project hierarchy
Was this page helpful?
⌘I