Skip to content

Commit fb13f66

Browse files
authored
Merge branch 'main' into add-detailer-mcp
2 parents 649c750 + d26ee26 commit fb13f66

8 files changed

Lines changed: 379 additions & 22 deletions

File tree

.vscode/settings.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{}

README.md

Lines changed: 18 additions & 15 deletions
Large diffs are not rendered by default.

src/everything/README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,14 @@ This MCP server attempts to exercise all the features of the MCP protocol. It is
7272
- Embedded resource with `type: "resource"`
7373
- Text instruction for using the resource URI
7474

75+
9. `startElicitation`
76+
- Initiates an elicitation (interaction) within the MCP client.
77+
- Inputs:
78+
- `color` (string): Favorite color
79+
- `number` (number, 1-100): Favorite number
80+
- `pets` (enum): Favorite pet
81+
- Returns: Confirmation of the elicitation demo with selection summary.
82+
7583
### Resources
7684

7785
The server provides 100 test resources in two formats:

src/everything/everything.ts

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,8 @@ const GetResourceReferenceSchema = z.object({
8686
.describe("ID of the resource to reference (1-100)"),
8787
});
8888

89+
const ElicitationSchema = z.object({});
90+
8991
const GetResourceLinksSchema = z.object({
9092
count: z
9193
.number()
@@ -104,6 +106,7 @@ enum ToolName {
104106
GET_TINY_IMAGE = "getTinyImage",
105107
ANNOTATED_MESSAGE = "annotatedMessage",
106108
GET_RESOURCE_REFERENCE = "getResourceReference",
109+
ELICITATION = "startElicitation",
107110
GET_RESOURCE_LINKS = "getResourceLinks",
108111
}
109112

@@ -126,6 +129,7 @@ export const createServer = () => {
126129
tools: {},
127130
logging: {},
128131
completions: {},
132+
elicitation: {},
129133
},
130134
instructions
131135
}
@@ -216,6 +220,21 @@ export const createServer = () => {
216220
return await server.request(request, CreateMessageResultSchema);
217221
};
218222

223+
const requestElicitation = async (
224+
message: string,
225+
requestedSchema: any
226+
) => {
227+
const request = {
228+
method: 'elicitation/create',
229+
params: {
230+
message,
231+
requestedSchema
232+
}
233+
};
234+
235+
return await server.request(request, z.any());
236+
};
237+
219238
const ALL_RESOURCES: Resource[] = Array.from({ length: 100 }, (_, i) => {
220239
const uri = `test://static/resource/${i + 1}`;
221240
if (i % 2 === 0) {
@@ -469,6 +488,11 @@ export const createServer = () => {
469488
"Returns a resource reference that can be used by MCP clients",
470489
inputSchema: zodToJsonSchema(GetResourceReferenceSchema) as ToolInput,
471490
},
491+
{
492+
name: ToolName.ELICITATION,
493+
description: "Demonstrates the Elicitation feature by asking the user to provide information about their favorite color, number, and pets.",
494+
inputSchema: zodToJsonSchema(ElicitationSchema) as ToolInput,
495+
},
472496
{
473497
name: ToolName.GET_RESOURCE_LINKS,
474498
description:
@@ -664,6 +688,61 @@ export const createServer = () => {
664688
return { content };
665689
}
666690

691+
if (name === ToolName.ELICITATION) {
692+
ElicitationSchema.parse(args);
693+
694+
const elicitationResult = await requestElicitation(
695+
'What are your favorite things?',
696+
{
697+
type: 'object',
698+
properties: {
699+
color: { type: 'string', description: 'Favorite color' },
700+
number: { type: 'integer', description: 'Favorite number', minimum: 1, maximum: 100 },
701+
pets: {
702+
type: 'string',
703+
enum: ['cats', 'dogs', 'birds', 'fish', 'reptiles'],
704+
description: 'Favorite pets'
705+
},
706+
}
707+
}
708+
);
709+
710+
// Handle different response actions
711+
const content = [];
712+
713+
if (elicitationResult.action === 'accept' && elicitationResult.content) {
714+
content.push({
715+
type: "text",
716+
text: `✅ User provided their favorite things!`,
717+
});
718+
719+
// Only access elicitationResult.content when action is accept
720+
const { color, number, pets } = elicitationResult.content;
721+
content.push({
722+
type: "text",
723+
text: `Their favorites are:\n- Color: ${color || 'not specified'}\n- Number: ${number || 'not specified'}\n- Pets: ${pets || 'not specified'}`,
724+
});
725+
} else if (elicitationResult.action === 'decline') {
726+
content.push({
727+
type: "text",
728+
text: `❌ User declined to provide their favorite things.`,
729+
});
730+
} else if (elicitationResult.action === 'cancel') {
731+
content.push({
732+
type: "text",
733+
text: `⚠️ User cancelled the elicitation dialog.`,
734+
});
735+
}
736+
737+
// Include raw result for debugging
738+
content.push({
739+
type: "text",
740+
text: `\nRaw result: ${JSON.stringify(elicitationResult, null, 2)}`,
741+
});
742+
743+
return { content };
744+
}
745+
667746
if (name === ToolName.GET_RESOURCE_LINKS) {
668747
const { count } = GetResourceLinksSchema.parse(args);
669748
const content = [];

src/filesystem/README.md

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,58 @@ Node.js server implementing Model Context Protocol (MCP) for filesystem operatio
99
- Move files/directories
1010
- Search files
1111
- Get file metadata
12+
- Dynamic directory access control via [Roots](https://modelcontextprotocol.io/docs/concepts/roots)
13+
14+
## Directory Access Control
15+
16+
The server uses a flexible directory access control system. Directories can be specified via command-line arguments or dynamically via [Roots](https://modelcontextprotocol.io/docs/concepts/roots).
17+
18+
### Method 1: Command-line Arguments
19+
Specify Allowed directories when starting the server:
20+
```bash
21+
mcp-server-filesystem /path/to/dir1 /path/to/dir2
22+
```
23+
24+
### Method 2: MCP Roots (Recommended)
25+
MCP clients that support [Roots](https://modelcontextprotocol.io/docs/concepts/roots) can dynamically update the Allowed directories.
26+
27+
Roots notified by Client to Server, completely replace any server-side Allowed directories when provided.
28+
29+
**Important**: If server starts without command-line arguments AND client doesn't support roots protocol (or provides empty roots), the server will throw an error during initialization.
30+
31+
This is the recommended method, as this enables runtime directory updates via `roots/list_changed` notifications without server restart, providing a more flexible and modern integration experience.
32+
33+
### How It Works
34+
35+
The server's directory access control follows this flow:
36+
37+
1. **Server Startup**
38+
- Server starts with directories from command-line arguments (if provided)
39+
- If no arguments provided, server starts with empty allowed directories
40+
41+
2. **Client Connection & Initialization**
42+
- Client connects and sends `initialize` request with capabilities
43+
- Server checks if client supports roots protocol (`capabilities.roots`)
44+
45+
3. **Roots Protocol Handling** (if client supports roots)
46+
- **On initialization**: Server requests roots from client via `roots/list`
47+
- Client responds with its configured roots
48+
- Server replaces ALL allowed directories with client's roots
49+
- **On runtime updates**: Client can send `notifications/roots/list_changed`
50+
- Server requests updated roots and replaces allowed directories again
51+
52+
4. **Fallback Behavior** (if client doesn't support roots)
53+
- Server continues using command-line directories only
54+
- No dynamic updates possible
55+
56+
5. **Access Control**
57+
- All filesystem operations are restricted to allowed directories
58+
- Use `list_allowed_directories` tool to see current directories
59+
- Server requires at least ONE allowed directory to operate
60+
61+
**Note**: The server will only allow operations within directories specified either via `args` or via Roots.
62+
1263

13-
**Note**: The server will only allow operations within directories specified via `args`.
1464

1565
## API
1666

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import { describe, it, expect, beforeEach, afterEach } from '@jest/globals';
2+
import { getValidRootDirectories } from '../roots-utils.js';
3+
import { mkdtempSync, rmSync, mkdirSync, writeFileSync, realpathSync } from 'fs';
4+
import { tmpdir } from 'os';
5+
import { join } from 'path';
6+
import type { Root } from '@modelcontextprotocol/sdk/types.js';
7+
8+
describe('getValidRootDirectories', () => {
9+
let testDir1: string;
10+
let testDir2: string;
11+
let testDir3: string;
12+
let testFile: string;
13+
14+
beforeEach(() => {
15+
// Create test directories
16+
testDir1 = realpathSync(mkdtempSync(join(tmpdir(), 'mcp-roots-test1-')));
17+
testDir2 = realpathSync(mkdtempSync(join(tmpdir(), 'mcp-roots-test2-')));
18+
testDir3 = realpathSync(mkdtempSync(join(tmpdir(), 'mcp-roots-test3-')));
19+
20+
// Create a test file (not a directory)
21+
testFile = join(testDir1, 'test-file.txt');
22+
writeFileSync(testFile, 'test content');
23+
});
24+
25+
afterEach(() => {
26+
// Cleanup
27+
rmSync(testDir1, { recursive: true, force: true });
28+
rmSync(testDir2, { recursive: true, force: true });
29+
rmSync(testDir3, { recursive: true, force: true });
30+
});
31+
32+
describe('valid directory processing', () => {
33+
it('should process all URI formats and edge cases', async () => {
34+
const roots = [
35+
{ uri: `file://${testDir1}`, name: 'File URI' },
36+
{ uri: testDir2, name: 'Plain path' },
37+
{ uri: testDir3 } // Plain path without name property
38+
];
39+
40+
const result = await getValidRootDirectories(roots);
41+
42+
expect(result).toContain(testDir1);
43+
expect(result).toContain(testDir2);
44+
expect(result).toContain(testDir3);
45+
expect(result).toHaveLength(3);
46+
});
47+
48+
it('should normalize complex paths', async () => {
49+
const subDir = join(testDir1, 'subdir');
50+
mkdirSync(subDir);
51+
52+
const roots = [
53+
{ uri: `file://${testDir1}/./subdir/../subdir`, name: 'Complex Path' }
54+
];
55+
56+
const result = await getValidRootDirectories(roots);
57+
58+
expect(result).toHaveLength(1);
59+
expect(result[0]).toBe(subDir);
60+
});
61+
});
62+
63+
describe('error handling', () => {
64+
65+
it('should handle various error types', async () => {
66+
const nonExistentDir = join(tmpdir(), 'non-existent-directory-12345');
67+
const invalidPath = '\0invalid\0path'; // Null bytes cause different error types
68+
const roots = [
69+
{ uri: `file://${testDir1}`, name: 'Valid Dir' },
70+
{ uri: `file://${nonExistentDir}`, name: 'Non-existent Dir' },
71+
{ uri: `file://${testFile}`, name: 'File Not Dir' },
72+
{ uri: `file://${invalidPath}`, name: 'Invalid Path' }
73+
];
74+
75+
const result = await getValidRootDirectories(roots);
76+
77+
expect(result).toContain(testDir1);
78+
expect(result).not.toContain(nonExistentDir);
79+
expect(result).not.toContain(testFile);
80+
expect(result).not.toContain(invalidPath);
81+
expect(result).toHaveLength(1);
82+
});
83+
});
84+
});

src/filesystem/index.ts

Lines changed: 62 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import {
66
CallToolRequestSchema,
77
ListToolsRequestSchema,
88
ToolSchema,
9+
RootsListChangedNotificationSchema,
10+
type Root,
911
} from "@modelcontextprotocol/sdk/types.js";
1012
import fs from "fs/promises";
1113
import path from "path";
@@ -16,12 +18,16 @@ import { zodToJsonSchema } from "zod-to-json-schema";
1618
import { diffLines, createTwoFilesPatch } from 'diff';
1719
import { minimatch } from 'minimatch';
1820
import { isPathWithinAllowedDirectories } from './path-validation.js';
21+
import { getValidRootDirectories } from './roots-utils.js';
1922

2023
// Command line argument parsing
2124
const args = process.argv.slice(2);
2225
if (args.length === 0) {
23-
console.error("Usage: mcp-server-filesystem <allowed-directory> [additional-directories...]");
24-
process.exit(1);
26+
console.error("Usage: mcp-server-filesystem [allowed-directory] [additional-directories...]");
27+
console.error("Note: Allowed directories can be provided via:");
28+
console.error(" 1. Command-line arguments (shown above)");
29+
console.error(" 2. MCP roots protocol (if client supports it)");
30+
console.error("At least one directory must be provided by EITHER method for the server to operate.");
2531
}
2632

2733
// Normalize all paths consistently
@@ -37,7 +43,7 @@ function expandHome(filepath: string): string {
3743
}
3844

3945
// Store allowed directories in normalized and resolved form
40-
const allowedDirectories = await Promise.all(
46+
let allowedDirectories = await Promise.all(
4147
args.map(async (dir) => {
4248
const expanded = expandHome(dir);
4349
const absolute = path.resolve(expanded);
@@ -573,8 +579,8 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
573579
{
574580
name: "list_allowed_directories",
575581
description:
576-
"Returns the list of directories that this server is allowed to access. " +
577-
"Use this to understand which directories are available before trying to access files.",
582+
"Returns the list of root directories that this server is allowed to access. " +
583+
"Use this to understand which directories are available before trying to access files. ",
578584
inputSchema: {
579585
type: "object",
580586
properties: {},
@@ -890,12 +896,62 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
890896
}
891897
});
892898

899+
// Updates allowed directories based on MCP client roots
900+
async function updateAllowedDirectoriesFromRoots(requestedRoots: Root[]) {
901+
const validatedRootDirs = await getValidRootDirectories(requestedRoots);
902+
if (validatedRootDirs.length > 0) {
903+
allowedDirectories = [...validatedRootDirs];
904+
console.error(`Updated allowed directories from MCP roots: ${validatedRootDirs.length} valid directories`);
905+
} else {
906+
console.error("No valid root directories provided by client");
907+
}
908+
}
909+
910+
// Handles dynamic roots updates during runtime, when client sends "roots/list_changed" notification, server fetches the updated roots and replaces all allowed directories with the new roots.
911+
server.setNotificationHandler(RootsListChangedNotificationSchema, async () => {
912+
try {
913+
// Request the updated roots list from the client
914+
const response = await server.listRoots();
915+
if (response && 'roots' in response) {
916+
await updateAllowedDirectoriesFromRoots(response.roots);
917+
}
918+
} catch (error) {
919+
console.error("Failed to request roots from client:", error instanceof Error ? error.message : String(error));
920+
}
921+
});
922+
923+
// Handles post-initialization setup, specifically checking for and fetching MCP roots.
924+
server.oninitialized = async () => {
925+
const clientCapabilities = server.getClientCapabilities();
926+
927+
if (clientCapabilities?.roots) {
928+
try {
929+
const response = await server.listRoots();
930+
if (response && 'roots' in response) {
931+
await updateAllowedDirectoriesFromRoots(response.roots);
932+
} else {
933+
console.error("Client returned no roots set, keeping current settings");
934+
}
935+
} catch (error) {
936+
console.error("Failed to request initial roots from client:", error instanceof Error ? error.message : String(error));
937+
}
938+
} else {
939+
if (allowedDirectories.length > 0) {
940+
console.error("Client does not support MCP Roots, using allowed directories set from server args:", allowedDirectories);
941+
}else{
942+
throw new Error(`Server cannot operate: No allowed directories available. Server was started without command-line directories and client either does not support MCP roots protocol or provided empty roots. Please either: 1) Start server with directory arguments, or 2) Use a client that supports MCP roots protocol and provides valid root directories.`);
943+
}
944+
}
945+
};
946+
893947
// Start server
894948
async function runServer() {
895949
const transport = new StdioServerTransport();
896950
await server.connect(transport);
897951
console.error("Secure MCP Filesystem Server running on stdio");
898-
console.error("Allowed directories:", allowedDirectories);
952+
if (allowedDirectories.length === 0) {
953+
console.error("Started without allowed directories - waiting for client to provide roots via MCP protocol");
954+
}
899955
}
900956

901957
runServer().catch((error) => {

0 commit comments

Comments
 (0)