Workspace Structure
curl --request GET \
--url https://api.example.com/resources/structureimport requests
url = "https://api.example.com/resources/structure"
response = requests.get(url)
print(response.text)const options = {method: 'GET'};
fetch('https://api.example.com/resources/structure', 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/structure",
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/structure"
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/structure")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.example.com/resources/structure")
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": "WORKSPACE_NOT_FOUND",
"message": "Workspace directory does not exist",
"details": {
"workspaceRoot": "/invalid/path"
}
}
}
{
"error": {
"code": "INVALID_PARAMETER",
"message": "maxDepth must be between 1 and 20",
"details": {
"parameter": "maxDepth",
"value": 50,
"min": 1,
"max": 20
}
}
}
{
"error": {
"code": "SCAN_TIMEOUT",
"message": "Workspace scan exceeded time limit",
"details": {
"timeout": 30000,
"suggestion": "Reduce maxDepth or add more excludePatterns"
}
}
}
API Reference
Workspace Structure
Get a hierarchical view of your Python project structure
GET
/
resources
/
structure
Workspace Structure
curl --request GET \
--url https://api.example.com/resources/structureimport requests
url = "https://api.example.com/resources/structure"
response = requests.get(url)
print(response.text)const options = {method: 'GET'};
fetch('https://api.example.com/resources/structure', 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/structure",
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/structure"
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/structure")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.example.com/resources/structure")
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": "WORKSPACE_NOT_FOUND",
"message": "Workspace directory does not exist",
"details": {
"workspaceRoot": "/invalid/path"
}
}
}
{
"error": {
"code": "INVALID_PARAMETER",
"message": "maxDepth must be between 1 and 20",
"details": {
"parameter": "maxDepth",
"value": 50,
"min": 1,
"max": 20
}
}
}
{
"error": {
"code": "SCAN_TIMEOUT",
"message": "Workspace scan exceeded time limit",
"details": {
"timeout": 30000,
"suggestion": "Reduce maxDepth or add more excludePatterns"
}
}
}
Overview
Theworkspace-structure resource returns a tree-like representation of your Python project, including directories, files, and module relationships.
Resource URI
pylance://workspace/structure
Request
string
required
Resource URI:
pylance://workspace/structurenumber
default:"10"
Maximum directory depth to traverse (1-20)
boolean
default:"false"
Include hidden files and directories (starting with
.)array
Glob patterns to exclude (e.g.,
["**/__pycache__/**", "**/.venv/**"])boolean
default:"true"
Include file counts, sizes, and module information
Response
object
Root directory node
Show Directory Node
Show Directory Node
string
Directory or file name
string
Relative path from workspace root
string
Node type:
directory or filearray
Child nodes (for directories)
number
Number of Python files (directories only)
number
Total size in bytes (directories only)
boolean
Whether directory is a Python package (has
__init__.py)string
Language identifier (files only)
number
File size in bytes (files only)
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://workspace/structure",
"params": {
"maxDepth": 5,
"includeHidden": false,
"excludePatterns": ["**/__pycache__/**", "**/.venv/**"]
}
}'
from pylance_mcp import MCPClient
client = MCPClient(api_key="YOUR_API_KEY")
structure = client.read_resource(
uri="pylance://workspace/structure",
maxDepth=5,
includeHidden=False,
excludePatterns=["**/__pycache__/**", "**/.venv/**"]
)
def print_tree(node, indent=0):
icon = "📁" if node["type"] == "directory" else "📄"
print(" " * indent + f"{icon} {node['name']}")
for child in node.get("children", []):
print_tree(child, indent + 1)
print_tree(structure["root"])
const { MCPClient } = require('@pylancemcp/client');
const client = new MCPClient({ apiKey: 'YOUR_API_KEY' });
const structure = await client.readResource({
uri: 'pylance://workspace/structure',
params: {
maxDepth: 5,
includeHidden: false,
excludePatterns: ['**/__pycache__/**', '**/.venv/**']
}
});
function printTree(node, indent = 0) {
const icon = node.type === 'directory' ? '📁' : '📄';
console.log(' '.repeat(indent) + `${icon} ${node.name}`);
(node.children || []).forEach(child => printTree(child, indent + 1));
}
printTree(structure.root);
import { MCPClient, WorkspaceStructure } from '@pylancemcp/client';
const client = new MCPClient({ apiKey: 'YOUR_API_KEY' });
const structure: WorkspaceStructure = await client.readResource({
uri: 'pylance://workspace/structure',
params: {
maxDepth: 5,
includeHidden: false,
excludePatterns: ['**/__pycache__/**', '**/.venv/**']
}
});
console.log(`Total files: ${structure.metadata.totalFiles}`);
console.log(`Packages: ${structure.metadata.packages.join(', ')}`);
Example Response
{
"root": {
"name": "workspace",
"path": "/",
"type": "directory",
"fileCount": 15,
"totalSize": 45678,
"isPackage": false,
"children": [
{
"name": "src",
"path": "/src",
"type": "directory",
"fileCount": 10,
"totalSize": 35000,
"isPackage": true,
"children": [
{
"name": "__init__.py",
"path": "/src/__init__.py",
"type": "file",
"language": "python",
"size": 256
},
{
"name": "main.py",
"path": "/src/main.py",
"type": "file",
"language": "python",
"size": 2048
},
{
"name": "models",
"path": "/src/models",
"type": "directory",
"fileCount": 4,
"totalSize": 15000,
"isPackage": true,
"children": [
{
"name": "__init__.py",
"path": "/src/models/__init__.py",
"type": "file",
"language": "python",
"size": 128
},
{
"name": "user.py",
"path": "/src/models/user.py",
"type": "file",
"language": "python",
"size": 4096
},
{
"name": "product.py",
"path": "/src/models/product.py",
"type": "file",
"language": "python",
"size": 3584
}
]
},
{
"name": "utils",
"path": "/src/utils",
"type": "directory",
"fileCount": 3,
"totalSize": 8000,
"isPackage": true,
"children": [
{
"name": "__init__.py",
"path": "/src/utils/__init__.py",
"type": "file",
"language": "python",
"size": 64
},
{
"name": "helpers.py",
"path": "/src/utils/helpers.py",
"type": "file",
"language": "python",
"size": 2048
}
]
}
]
},
{
"name": "tests",
"path": "/tests",
"type": "directory",
"fileCount": 5,
"totalSize": 10678,
"isPackage": true,
"children": [
{
"name": "__init__.py",
"path": "/tests/__init__.py",
"type": "file",
"language": "python",
"size": 0
},
{
"name": "test_user.py",
"path": "/tests/test_user.py",
"type": "file",
"language": "python",
"size": 3456
}
]
}
]
},
"metadata": {
"totalFiles": 15,
"totalDirectories": 6,
"packages": ["src", "src.models", "src.utils", "tests"],
"depth": 3,
"totalSize": 45678
}
}
Common Use Cases
Visualize Project Structure
def visualize_structure(node, indent=0, is_last=True):
prefix = "└── " if is_last else "├── "
connector = " " if is_last else "│ "
if indent > 0:
print(connector * (indent - 1) + prefix + node["name"])
else:
print(node["name"])
children = node.get("children", [])
for i, child in enumerate(children):
is_last_child = i == len(children) - 1
visualize_structure(child, indent + 1, is_last_child)
structure = client.read_resource(uri="pylance://workspace/structure")
visualize_structure(structure["root"])
workspace
├── src
│ ├── __init__.py
│ ├── main.py
│ ├── models
│ │ ├── __init__.py
│ │ ├── user.py
│ │ └── product.py
│ └── utils
│ ├── __init__.py
│ └── helpers.py
└── tests
├── __init__.py
└── test_user.py
Find All Packages
structure = client.read_resource(
uri="pylance://workspace/structure",
includeMetadata=True
)
packages = structure["metadata"]["packages"]
print(f"Found {len(packages)} packages:")
for pkg in packages:
print(f" - {pkg}")
Calculate Project Size
structure = client.read_resource(uri="pylance://workspace/structure")
def format_size(bytes):
for unit in ['B', 'KB', 'MB', 'GB']:
if bytes < 1024:
return f"{bytes:.2f} {unit}"
bytes /= 1024
return f"{bytes:.2f} TB"
total_size = structure["metadata"]["totalSize"]
print(f"Project size: {format_size(total_size)}")
Find Large Directories
def find_large_dirs(node, threshold=10000, results=None):
if results is None:
results = []
if node["type"] == "directory":
if node["totalSize"] > threshold:
results.append({
"path": node["path"],
"size": node["totalSize"],
"fileCount": node["fileCount"]
})
for child in node.get("children", []):
find_large_dirs(child, threshold, results)
return results
structure = client.read_resource(uri="pylance://workspace/structure")
large_dirs = find_large_dirs(structure["root"], threshold=50000)
for dir in sorted(large_dirs, key=lambda x: x["size"], reverse=True):
print(f"{dir['path']}: {dir['size']} bytes ({dir['fileCount']} files)")
Performance Considerations
Large workspaces (>1,000 files) may take several seconds to scan. Use
maxDepth to limit traversal.Optimization Tips
Set
maxDepth to minimum required depthUse
excludePatterns to skip unnecessary directoriesSet
includeMetadata=false if counts aren’t neededCache structure and invalidate on workspace changes
# Fast scan of top 2 levels only
structure = client.read_resource(
uri="pylance://workspace/structure",
maxDepth=2,
includeMetadata=False
)
Error Responses
{
"error": {
"code": "WORKSPACE_NOT_FOUND",
"message": "Workspace directory does not exist",
"details": {
"workspaceRoot": "/invalid/path"
}
}
}
{
"error": {
"code": "INVALID_PARAMETER",
"message": "maxDepth must be between 1 and 20",
"details": {
"parameter": "maxDepth",
"value": 50,
"min": 1,
"max": 20
}
}
}
{
"error": {
"code": "SCAN_TIMEOUT",
"message": "Workspace scan exceeded time limit",
"details": {
"timeout": 30000,
"suggestion": "Reduce maxDepth or add more excludePatterns"
}
}
}
Rate Limits
| Tier | Requests/Day | Max Depth |
|---|---|---|
| Free | 50 | 5 |
| Hobby | 1,000 | 10 |
| Pro | 10,000 | 20 |
| Enterprise | Unlimited | Unlimited |
Related Resources
List Files
Get flat list of all files
Read File
Read individual file contents
Was this page helpful?
⌘I