Skip to content

Commit a5ce2d6

Browse files
committed
fix(filesystem): preserve root aliases from MCP roots
Fixes modelcontextprotocol#4129
1 parent b1e1eb1 commit a5ce2d6

2 files changed

Lines changed: 69 additions & 25 deletions

File tree

‎src/filesystem/__tests__/roots-utils.test.ts‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
22
import { getValidRootDirectories } from '../roots-utils.js';
3-
import { mkdtempSync, rmSync, mkdirSync, writeFileSync, realpathSync } from 'fs';
3+
import { mkdtempSync, rmSync, mkdirSync, writeFileSync, realpathSync, symlinkSync } from 'fs';
44
import { tmpdir } from 'os';
55
import { join } from 'path';
66
import type { Root } from '@modelcontextprotocol/sdk/types.js';
@@ -48,7 +48,7 @@ describe('getValidRootDirectories', () => {
4848
it('should normalize complex paths', async () => {
4949
const subDir = join(testDir1, 'subdir');
5050
mkdirSync(subDir);
51-
51+
5252
const roots = [
5353
{ uri: `file://${testDir1}/./subdir/../subdir`, name: 'Complex Path' }
5454
];
@@ -58,6 +58,32 @@ describe('getValidRootDirectories', () => {
5858
expect(result).toHaveLength(1);
5959
expect(result[0]).toBe(subDir);
6060
});
61+
62+
it('keeps both original and resolved forms for roots that resolve differently', async () => {
63+
const realDir = join(testDir1, 'real-root');
64+
const aliasDir = join(testDir1, 'alias-root');
65+
mkdirSync(realDir);
66+
67+
try {
68+
symlinkSync(realDir, aliasDir);
69+
} catch (error) {
70+
if ((error as NodeJS.ErrnoException).code === 'EPERM') {
71+
return;
72+
}
73+
throw error;
74+
}
75+
76+
const roots: Root[] = [
77+
{ uri: `file://${aliasDir}`, name: 'Symlink Root' }
78+
];
79+
80+
const result = await getValidRootDirectories(roots);
81+
const resolvedDir = realpathSync(aliasDir);
82+
83+
expect(result).toContain(aliasDir);
84+
expect(result).toContain(resolvedDir);
85+
expect(result).toHaveLength(2);
86+
});
6187
});
6288

6389
describe('error handling', () => {
@@ -81,4 +107,4 @@ describe('getValidRootDirectories', () => {
81107
expect(result).toHaveLength(1);
82108
});
83109
});
84-
});
110+
});

‎src/filesystem/roots-utils.ts‎

Lines changed: 40 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,30 @@ import type { Root } from '@modelcontextprotocol/sdk/types.js';
66
import { fileURLToPath } from "url";
77

88
/**
9-
* Converts a root URI to a normalized directory path with basic security validation.
9+
* Converts a root URI to normalized directory paths with basic security validation.
10+
*
11+
* Returns both the original normalized path and the resolved path when they differ.
12+
* This keeps roots-provided directories symmetric with command-line directories,
13+
* so paths addressed through either a symlink/mapped-drive form or its resolved
14+
* target continue to pass allow-list validation.
15+
*
1016
* @param rootUri - File URI (file://...) or plain directory path
11-
* @returns Promise resolving to validated path or null if invalid
17+
* @returns Promise resolving to validated paths or null if invalid
1218
*/
13-
async function parseRootUri(rootUri: string): Promise<string | null> {
19+
async function parseRootUri(rootUri: string): Promise<string[] | null> {
1420
try {
1521
const rawPath = rootUri.startsWith('file://') ? fileURLToPath(rootUri) : rootUri;
16-
const expandedPath = rawPath.startsWith('~/') || rawPath === '~'
17-
? path.join(os.homedir(), rawPath.slice(1))
22+
const expandedPath = rawPath.startsWith('~/') || rawPath === '~'
23+
? path.join(os.homedir(), rawPath.slice(1))
1824
: rawPath;
1925
const absolutePath = path.resolve(expandedPath);
26+
const normalizedOriginal = normalizePath(absolutePath);
2027
const resolvedPath = await fs.realpath(absolutePath);
21-
return normalizePath(resolvedPath);
28+
const normalizedResolved = normalizePath(resolvedPath);
29+
30+
return normalizedOriginal === normalizedResolved
31+
? [normalizedResolved]
32+
: [normalizedOriginal, normalizedResolved];
2233
} catch {
2334
return null; // Path doesn't exist or other error
2435
}
@@ -41,37 +52,44 @@ function formatDirectoryError(dir: string, error?: unknown, reason?: string): st
4152

4253
/**
4354
* Resolves requested root directories from MCP root specifications.
44-
*
55+
*
4556
* Converts root URI specifications (file:// URIs or plain paths) into normalized
4657
* directory paths, validating that each path exists and is a directory.
4758
* Includes symlink resolution for security.
48-
*
59+
*
4960
* @param requestedRoots - Array of root specifications with URI and optional name
5061
* @returns Promise resolving to array of validated directory paths
5162
*/
5263
export async function getValidRootDirectories(
5364
requestedRoots: readonly Root[]
5465
): Promise<string[]> {
5566
const validatedDirectories: string[] = [];
56-
67+
const seenDirectories = new Set<string>();
68+
5769
for (const requestedRoot of requestedRoots) {
58-
const resolvedPath = await parseRootUri(requestedRoot.uri);
59-
if (!resolvedPath) {
70+
const candidatePaths = await parseRootUri(requestedRoot.uri);
71+
if (!candidatePaths) {
6072
console.error(formatDirectoryError(requestedRoot.uri, undefined, 'invalid path or inaccessible'));
6173
continue;
6274
}
63-
64-
try {
65-
const stats: Stats = await fs.stat(resolvedPath);
66-
if (stats.isDirectory()) {
67-
validatedDirectories.push(resolvedPath);
68-
} else {
69-
console.error(formatDirectoryError(resolvedPath, undefined, 'non-directory root'));
75+
76+
for (const candidatePath of candidatePaths) {
77+
try {
78+
const stats: Stats = await fs.stat(candidatePath);
79+
if (!stats.isDirectory()) {
80+
console.error(formatDirectoryError(candidatePath, undefined, 'non-directory root'));
81+
continue;
82+
}
83+
84+
if (!seenDirectories.has(candidatePath)) {
85+
validatedDirectories.push(candidatePath);
86+
seenDirectories.add(candidatePath);
87+
}
88+
} catch (error) {
89+
console.error(formatDirectoryError(candidatePath, error));
7090
}
71-
} catch (error) {
72-
console.error(formatDirectoryError(resolvedPath, error));
7391
}
7492
}
75-
93+
7694
return validatedDirectories;
77-
}
95+
}

0 commit comments

Comments
 (0)