Repository navigation
Expand file tree
/
Copy pathroots-utils.ts
More file actions
111 lines (104 loc) · 3.63 KB
/
Copy pathroots-utils.ts
File metadata and controls
111 lines (104 loc) · 3.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import { promises as fs, type Stats } from "fs";
import path from "path";
import {
normalizePathFormat,
realpathWithRetry,
expandHome,
} from "./path-utils.js";
import type { Root } from "@modelcontextprotocol/server";
import { fileURLToPath } from "url";
/** A root's two spellings: as the client advertised it, and its realpath. */
interface RootPaths {
advertised: string;
resolved: string;
}
/**
* Converts a root URI to its normalized absolute path and its realpath.
* Both are kept, as resolveAllowedDirectories in index.ts keeps both forms of
* a command-line directory, so a request may use either spelling (#5183).
* validatePath still realpaths every request, so access stays bounded by the
* resolved directory.
* @param rootUri - File URI (file://...) or plain directory path
* @returns Promise resolving to both forms, or null if invalid
*/
async function parseRootUri(rootUri: string): Promise<RootPaths | null> {
try {
const rawPath = rootUri.startsWith("file://")
? fileURLToPath(rootUri)
: rootUri;
const expandedPath = expandHome(rawPath);
const absolutePath = path.resolve(expandedPath);
const resolvedPath = await realpathWithRetry(absolutePath);
return {
// normalizePathFormat, not normalizePath, for both: trimming whitespace
// or quotes from the client's spelling or from the realpath would name
// a different directory, and allow it (#5183, #5320).
advertised: normalizePathFormat(absolutePath),
resolved: normalizePathFormat(resolvedPath),
};
} catch {
return null; // Path doesn't exist or other error
}
}
/**
* Formats error message for directory validation failures.
* @param dir - Directory path that failed validation
* @param error - Error that occurred during validation
* @param reason - Specific reason for failure
* @returns Formatted error message
*/
function formatDirectoryError(
dir: string,
error?: unknown,
reason?: string,
): string {
if (reason) {
return `Skipping ${reason}: ${dir}`;
}
const message = error instanceof Error ? error.message : String(error);
return `Skipping invalid directory: ${dir} due to error: ${message}`;
}
/**
* Resolves requested root directories from MCP root specifications.
*
* Converts root URI specifications (file:// URIs or plain paths) into normalized
* directory paths, validating that each path exists and is a directory.
* Each root contributes its advertised form and, when it differs, its resolved
* (realpath) form, deduplicated across roots.
*
* @param requestedRoots - Array of root specifications with URI and optional name
* @returns Promise resolving to array of validated directory paths
*/
export async function getValidRootDirectories(
requestedRoots: readonly Root[],
): Promise<string[]> {
const validatedDirectories = new Set<string>();
for (const requestedRoot of requestedRoots) {
const rootPaths = await parseRootUri(requestedRoot.uri);
if (!rootPaths) {
console.error(
formatDirectoryError(
requestedRoot.uri,
undefined,
"invalid path or inaccessible",
),
);
continue;
}
const { advertised, resolved: resolvedPath } = rootPaths;
try {
const stats: Stats = await fs.stat(resolvedPath);
if (stats.isDirectory()) {
validatedDirectories.add(advertised);
validatedDirectories.add(resolvedPath);
} else {
console.error(
formatDirectoryError(resolvedPath, undefined, "non-directory root"),
);
}
} catch (error) {
console.error(formatDirectoryError(resolvedPath, error));
}
}
return [...validatedDirectories];
}