@j0hanz/filesystem-mcp 2.1.7 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -9
- package/dist/cli.d.ts +1 -2
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +29 -34
- package/dist/cli.js.map +1 -1
- package/dist/core/concurrency.d.ts +4 -7
- package/dist/core/concurrency.d.ts.map +1 -1
- package/dist/core/concurrency.js +4 -12
- package/dist/core/concurrency.js.map +1 -1
- package/dist/core/cursor.d.ts +11 -0
- package/dist/core/cursor.d.ts.map +1 -1
- package/dist/core/cursor.js +18 -20
- package/dist/core/cursor.js.map +1 -1
- package/dist/core/fmt.d.ts +2 -1
- package/dist/core/fmt.d.ts.map +1 -1
- package/dist/core/fmt.js +8 -15
- package/dist/core/fmt.js.map +1 -1
- package/dist/core/fs.d.ts +0 -14
- package/dist/core/fs.d.ts.map +1 -1
- package/dist/core/fs.js +1 -0
- package/dist/core/fs.js.map +1 -1
- package/dist/core/glob.d.ts +4 -16
- package/dist/core/glob.d.ts.map +1 -1
- package/dist/core/glob.js +16 -33
- package/dist/core/glob.js.map +1 -1
- package/dist/core/input-required.d.ts +10 -2
- package/dist/core/input-required.d.ts.map +1 -1
- package/dist/core/input-required.js +10 -0
- package/dist/core/input-required.js.map +1 -1
- package/dist/core/observability.d.ts.map +1 -1
- package/dist/core/observability.js +2 -1
- package/dist/core/observability.js.map +1 -1
- package/dist/core/path-completer.d.ts.map +1 -1
- package/dist/core/path-completer.js +4 -27
- package/dist/core/path-completer.js.map +1 -1
- package/dist/core/path-utils.d.ts +1 -1
- package/dist/core/path-utils.d.ts.map +1 -1
- package/dist/core/path-utils.js +2 -2
- package/dist/core/path-utils.js.map +1 -1
- package/dist/core/path.d.ts +7 -9
- package/dist/core/path.d.ts.map +1 -1
- package/dist/core/path.js +24 -42
- package/dist/core/path.js.map +1 -1
- package/dist/core/primitives.d.ts +7 -0
- package/dist/core/primitives.d.ts.map +1 -1
- package/dist/core/primitives.js +15 -8
- package/dist/core/primitives.js.map +1 -1
- package/dist/core/read.d.ts.map +1 -1
- package/dist/core/read.js +6 -23
- package/dist/core/read.js.map +1 -1
- package/dist/core/schema.d.ts.map +1 -1
- package/dist/core/schema.js +19 -74
- package/dist/core/schema.js.map +1 -1
- package/dist/core/search.d.ts +4 -11
- package/dist/core/search.d.ts.map +1 -1
- package/dist/core/search.js +11 -18
- package/dist/core/search.js.map +1 -1
- package/dist/core/store.d.ts.map +1 -1
- package/dist/core/store.js +6 -17
- package/dist/core/store.js.map +1 -1
- package/dist/core/util.d.ts.map +1 -1
- package/dist/core/util.js +2 -11
- package/dist/core/util.js.map +1 -1
- package/dist/index.js +15 -42
- package/dist/index.js.map +1 -1
- package/dist/instructions.js +11 -11
- package/dist/instructions.js.map +1 -1
- package/dist/prompts.d.ts.map +1 -1
- package/dist/prompts.js +17 -25
- package/dist/prompts.js.map +1 -1
- package/dist/resources.d.ts +4 -4
- package/dist/resources.d.ts.map +1 -1
- package/dist/resources.js +7 -17
- package/dist/resources.js.map +1 -1
- package/dist/server.d.ts +1 -12
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +15 -30
- package/dist/server.js.map +1 -1
- package/dist/tools/define.d.ts.map +1 -1
- package/dist/tools/define.js +39 -65
- package/dist/tools/define.js.map +1 -1
- package/dist/tools/delete.d.ts +2 -0
- package/dist/tools/delete.d.ts.map +1 -0
- package/dist/tools/{delete-file.js → delete.js} +35 -40
- package/dist/tools/delete.js.map +1 -0
- package/dist/tools/find-files.d.ts +2 -0
- package/dist/tools/find-files.d.ts.map +1 -0
- package/dist/tools/{search-files.js → find-files.js} +14 -19
- package/dist/tools/find-files.js.map +1 -0
- package/dist/tools/index.d.ts +6 -6
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +15 -15
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/list-roots.d.ts +2 -0
- package/dist/tools/list-roots.d.ts.map +1 -0
- package/dist/tools/{roots.js → list-roots.js} +2 -2
- package/dist/tools/list-roots.js.map +1 -0
- package/dist/tools/list.d.ts.map +1 -1
- package/dist/tools/list.js +29 -37
- package/dist/tools/list.js.map +1 -1
- package/dist/tools/move.d.ts.map +1 -1
- package/dist/tools/move.js +5 -7
- package/dist/tools/move.js.map +1 -1
- package/dist/tools/progress.d.ts +1 -1
- package/dist/tools/progress.d.ts.map +1 -1
- package/dist/tools/progress.js.map +1 -1
- package/dist/tools/read.d.ts +1 -1
- package/dist/tools/read.d.ts.map +1 -1
- package/dist/tools/read.js +37 -43
- package/dist/tools/read.js.map +1 -1
- package/dist/tools/replace-text.d.ts +2 -0
- package/dist/tools/replace-text.d.ts.map +1 -0
- package/dist/tools/{replace-in-files.js → replace-text.js} +9 -23
- package/dist/tools/replace-text.js.map +1 -0
- package/dist/tools/search-text.d.ts +2 -0
- package/dist/tools/search-text.d.ts.map +1 -0
- package/dist/tools/{search-content.js → search-text.js} +10 -37
- package/dist/tools/search-text.js.map +1 -0
- package/dist/tools/stat.d.ts +1 -1
- package/dist/tools/stat.d.ts.map +1 -1
- package/dist/tools/stat.js +10 -38
- package/dist/tools/stat.js.map +1 -1
- package/dist/transport/http-policy.d.ts +18 -15
- package/dist/transport/http-policy.d.ts.map +1 -1
- package/dist/transport/http-policy.js +29 -39
- package/dist/transport/http-policy.js.map +1 -1
- package/dist/transport/http.d.ts.map +1 -1
- package/dist/transport/http.js +29 -39
- package/dist/transport/http.js.map +1 -1
- package/package.json +4 -7
- package/dist/tools/delete-file.d.ts +0 -2
- package/dist/tools/delete-file.d.ts.map +0 -1
- package/dist/tools/delete-file.js.map +0 -1
- package/dist/tools/replace-in-files.d.ts +0 -2
- package/dist/tools/replace-in-files.d.ts.map +0 -1
- package/dist/tools/replace-in-files.js.map +0 -1
- package/dist/tools/roots.d.ts +0 -2
- package/dist/tools/roots.d.ts.map +0 -1
- package/dist/tools/roots.js.map +0 -1
- package/dist/tools/search-content.d.ts +0 -2
- package/dist/tools/search-content.d.ts.map +0 -1
- package/dist/tools/search-content.js.map +0 -1
- package/dist/tools/search-files.d.ts +0 -2
- package/dist/tools/search-files.d.ts.map +0 -1
- package/dist/tools/search-files.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -35,29 +35,17 @@ async function shutdown(reason, exitCode = 0) {
|
|
|
35
35
|
}, SHUTDOWN_TIMEOUT_MS);
|
|
36
36
|
timer.unref();
|
|
37
37
|
try {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
try {
|
|
41
|
-
await new Promise((resolve, reject) => {
|
|
42
|
-
server.close((err) => {
|
|
43
|
-
if (err)
|
|
44
|
-
reject(err);
|
|
45
|
-
else
|
|
46
|
-
resolve();
|
|
47
|
-
});
|
|
48
|
-
});
|
|
49
|
-
}
|
|
50
|
-
catch (error) {
|
|
51
|
-
logRuntimeFailure('shutdown_http_error', 'process', 'shutdown', error);
|
|
52
|
-
}
|
|
38
|
+
try {
|
|
39
|
+
await activeHttpServer?.[Symbol.asyncDispose]();
|
|
53
40
|
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
41
|
+
catch (error) {
|
|
42
|
+
logRuntimeFailure('shutdown_http_error', 'process', 'shutdown', error);
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
await activeStdioHandle?.close();
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
logRuntimeFailure('shutdown_mcp_error', 'process', 'shutdown', error);
|
|
61
49
|
}
|
|
62
50
|
}
|
|
63
51
|
finally {
|
|
@@ -65,37 +53,22 @@ async function shutdown(reason, exitCode = 0) {
|
|
|
65
53
|
}
|
|
66
54
|
}
|
|
67
55
|
async function main() {
|
|
68
|
-
let
|
|
69
|
-
let allowCwd;
|
|
70
|
-
let port;
|
|
71
|
-
let readOnly;
|
|
72
|
-
let printConfig;
|
|
73
|
-
let json;
|
|
74
|
-
let httpHost;
|
|
75
|
-
let cliApiKey;
|
|
56
|
+
let parsed;
|
|
76
57
|
try {
|
|
77
|
-
|
|
78
|
-
allowedDirs = parsed.allowedDirs;
|
|
79
|
-
allowCwd = parsed.allowCwd;
|
|
80
|
-
port = parsed.port;
|
|
81
|
-
readOnly = parsed.readOnly;
|
|
82
|
-
printConfig = parsed.printConfig;
|
|
83
|
-
json = parsed.json;
|
|
84
|
-
httpHost = parsed.httpHost;
|
|
85
|
-
cliApiKey = parsed.apiKey;
|
|
58
|
+
parsed = await parseArgs();
|
|
86
59
|
}
|
|
87
60
|
catch (error) {
|
|
88
61
|
if (error instanceof CliExitError) {
|
|
89
62
|
if (error.message.length > 0) {
|
|
90
63
|
logRuntimeFailure('cli_exit', 'startup', 'parse_args', error.message);
|
|
91
64
|
}
|
|
92
|
-
process.exitCode =
|
|
65
|
+
process.exitCode = 1;
|
|
93
66
|
return;
|
|
94
67
|
}
|
|
95
68
|
throw error;
|
|
96
69
|
}
|
|
70
|
+
const { allowedDirs, allowCwd, port, readOnly, printConfig, json, httpHost, apiKey } = parsed;
|
|
97
71
|
if (printConfig) {
|
|
98
|
-
const apiKey = cliApiKey;
|
|
99
72
|
await runPrintConfig({
|
|
100
73
|
allowedDirs,
|
|
101
74
|
allowCwd,
|
|
@@ -122,7 +95,7 @@ async function main() {
|
|
|
122
95
|
const serverOptions = { allowCwd, cliAllowedDirs: allowedDirs, readOnly };
|
|
123
96
|
const runtimeConfig = {
|
|
124
97
|
...(httpHost !== undefined ? { httpHost } : {}),
|
|
125
|
-
...(
|
|
98
|
+
...(apiKey !== undefined ? { apiKey } : {}),
|
|
126
99
|
};
|
|
127
100
|
if (port !== undefined) {
|
|
128
101
|
activeHttpServer = await startHttpServer(port, serverOptions, runtimeConfig);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAKA,OAAO,OAAO,MAAM,cAAc,CAAC;AAEn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AC,oBAAoB,EAAE,CAAC,CAAC,CAAC;AACzC,CAAC,CAAC,CAAC;AAEH,OAAO,CAAC,IAAI,CAAC,mBAAmB,EAAE,CAAC,KAAY,EAAE,EAAE;IACjD,iBAAiB,CAAC,oBAAoB,EAAE,SAAS,EAAE,mBAAmB,EAAE,KAAK,CAAC,CAAC;IAC/E,KAAK,QAAQ,CAAC,mBAAmB,EAAE,CAAC,CAAC,CAAC;AACxC,CAAC,CAAC,CAAC;AAEH,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC9B,iBAAiB,CAAC,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;IACrD,KAAK,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;AAC5B,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n// Type-only imports are erased at runtime — safe to keep static.\nimport type { StdioServerHandle } from '@modelcontextprotocol/server/stdio';\n\nimport type * as http from 'node:http';\nimport process from 'node:process';\n\nimport * as z from 'zod/v4';\n\nimport { CliExitError, parseArgs, runPrintConfig } from './cli.js';\nimport { NO_POSITIONAL_ROOTS_GUIDANCE } from './core/config.js';\nimport { logRuntimeFailure } from './core/observability.js';\nimport { startHttpServer, startServer } from './transport.js';\n\nz.config(z.locales.en());\n\nconst SHUTDOWN_TIMEOUT_MS = 5000;\nlet activeStdioHandle: StdioServerHandle | undefined;\nlet activeHttpServer: http.Server | undefined;\nlet shutdownStarted = false;\n\nfunction isStdinEvent(event: NodeJS.Signals | 'end' | 'close'): boolean {\n return event === 'end' || event === 'close';\n}\n\nfunction registerShutdownTrigger(event: NodeJS.Signals | 'end' | 'close'): void {\n const target = isStdinEvent(event) ? process.stdin : process;\n target.once(event, () => {\n const reason = isStdinEvent(event) ? `stdin ${event}` : event;\n void shutdown(reason, 0);\n });\n}\n\nasync function shutdown(reason: string, exitCode = 0): Promise<void> {\n if (shutdownStarted) {\n if (reason === 'SIGINT' || reason === 'SIGTERM') {\n process.exit(130);\n }\n return;\n }\n shutdownStarted = true;\n\n process.exitCode = exitCode;\n\n const timer = setTimeout(() => {\n logRuntimeFailure(\n 'shutdown_timeout',\n 'process',\n 'shutdown',\n `Shutdown timed out (${reason}), forcing exit.`,\n );\n process.exit(exitCode);\n }, SHUTDOWN_TIMEOUT_MS);\n timer.unref();\n\n try {\n try {\n await activeHttpServer?.[Symbol.asyncDispose]();\n } catch (error: unknown) {\n logRuntimeFailure('shutdown_http_error', 'process', 'shutdown', error);\n }\n try {\n await activeStdioHandle?.close();\n } catch (error: unknown) {\n logRuntimeFailure('shutdown_mcp_error', 'process', 'shutdown', error);\n }\n } finally {\n clearTimeout(timer);\n }\n}\n\nasync function main(): Promise<void> {\n let parsed: Awaited<ReturnType<typeof parseArgs>>;\n try {\n parsed = await parseArgs();\n } catch (error: unknown) {\n if (error instanceof CliExitError) {\n if (error.message.length > 0) {\n logRuntimeFailure('cli_exit', 'startup', 'parse_args', error.message);\n }\n process.exitCode = 1;\n return;\n }\n throw error;\n }\n const { allowedDirs, allowCwd, port, readOnly, printConfig, json, httpHost, apiKey } = parsed;\n\n if (printConfig) {\n await runPrintConfig({\n allowedDirs,\n allowCwd,\n readOnly,\n json,\n ...(port !== undefined ? { port } : {}),\n ...(httpHost !== undefined ? { httpHost } : {}),\n ...(apiKey !== undefined ? { apiKey } : {}),\n });\n return;\n }\n\n if (allowedDirs.length > 0) {\n console.error('Allowed directories (from CLI):');\n for (const dir of allowedDirs) {\n console.error(`- ${dir}`);\n }\n } else {\n console.error(NO_POSITIONAL_ROOTS_GUIDANCE);\n }\n\n if (readOnly) {\n console.error('Read-only mode: mutating tools disabled.');\n }\n\n const serverOptions = { allowCwd, cliAllowedDirs: allowedDirs, readOnly };\n const runtimeConfig = {\n ...(httpHost !== undefined ? { httpHost } : {}),\n ...(apiKey !== undefined ? { apiKey } : {}),\n };\n\n if (port !== undefined) {\n activeHttpServer = await startHttpServer(port, serverOptions, runtimeConfig);\n } else {\n registerShutdownTrigger('end');\n registerShutdownTrigger('close');\n activeStdioHandle = startServer(serverOptions, runtimeConfig);\n }\n}\n\nregisterShutdownTrigger('SIGTERM');\nregisterShutdownTrigger('SIGINT');\n\nprocess.once('unhandledRejection', (reason: unknown) => {\n logRuntimeFailure('unhandled_rejection', 'process', 'unhandledRejection', reason);\n void shutdown('unhandledRejection', 1);\n});\n\nprocess.once('uncaughtException', (error: Error) => {\n logRuntimeFailure('uncaught_exception', 'process', 'uncaughtException', error);\n void shutdown('uncaughtException', 1);\n});\n\nmain().catch((error: unknown) => {\n logRuntimeFailure('fatal', 'startup', 'main', error);\n void shutdown('fatal', 1);\n});\n"]}
|
package/dist/instructions.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { DEFAULT_SEARCH_CONTENT_RESULTS, getMaxTextFileSize, MAX_SEARCH_RESULTS, } from './core/util.js';
|
|
2
|
-
import {
|
|
2
|
+
import { FIND_FILES, LIST, LIST_ROOTS, MUTATING_TOOL_NAMES, READ, SEARCH_TEXT, STAT, } from './tools/index.js';
|
|
3
3
|
function buildToolsOverview(readOnly) {
|
|
4
4
|
const rows = [
|
|
5
|
-
['Navigate', [
|
|
6
|
-
['Inspect', [
|
|
7
|
-
['Read', [
|
|
5
|
+
['Navigate', [LIST_ROOTS.name, LIST.name, FIND_FILES.name]],
|
|
6
|
+
['Inspect', [STAT.name, SEARCH_TEXT.name]],
|
|
7
|
+
['Read', [READ.name]],
|
|
8
8
|
];
|
|
9
9
|
// Under --read-only the mutating tools are never registered, so advertising
|
|
10
10
|
// them here would point the model at tools that are not there. Drop the row
|
|
@@ -30,9 +30,9 @@ export function buildSectionsRecord(readOnly) {
|
|
|
30
30
|
guidelines: [
|
|
31
31
|
'Guidelines:',
|
|
32
32
|
'```',
|
|
33
|
-
`root_access: ${
|
|
33
|
+
`root_access: ${LIST_ROOTS.name} lists configured or accepted roots; every other tool is scoped to them.`,
|
|
34
34
|
'modern_root_grants: Modern clients do not automatically send workspace roots. Call a tool with a concrete path and approve its grant when elicitation is available.',
|
|
35
|
-
`path_resolution: Confirm a path with ${LIST.name} or ${
|
|
35
|
+
`path_resolution: Confirm a path with ${LIST.name} or ${FIND_FILES.name} before acting on it.`,
|
|
36
36
|
'```',
|
|
37
37
|
].join('\n'),
|
|
38
38
|
tools_overview: [
|
|
@@ -44,20 +44,20 @@ export function buildSectionsRecord(readOnly) {
|
|
|
44
44
|
constraints: [
|
|
45
45
|
'Constraints:',
|
|
46
46
|
'```',
|
|
47
|
-
`allowed_roots: Startup roots come from CLI paths, FS_ALLOWED_DIRS, or --allow-cwd; accepted modern grants are additive. Call ${
|
|
47
|
+
`allowed_roots: Startup roots come from CLI paths, FS_ALLOWED_DIRS, or --allow-cwd; accepted modern grants are additive. Call ${LIST_ROOTS.name} to read the current set.`,
|
|
48
48
|
'legacy_roots: Legacy clients may additionally seed roots through the deprecated roots/list flow.',
|
|
49
49
|
'sensitive_paths: Sensitive file paths (.env, *.pem, *id_rsa*) are denied by default.',
|
|
50
50
|
`enforced_limits: max file size ${maxFileMb} MB, file search cap ${MAX_SEARCH_RESULTS} results, content search cap ${DEFAULT_SEARCH_CONTENT_RESULTS} matches.`,
|
|
51
51
|
'ephemeral_results: When a result carries a resource_link or a resourceUri (in structuredContent or _meta), call resources/read immediately — cached results are ephemeral and expire after ~60 seconds, eviction, or restart.',
|
|
52
|
-
'pagination: nextCursor appears in the text
|
|
52
|
+
'pagination: nextCursor appears in the result text and in _meta, backed by a snapshot on the same ~60s clock. Page through promptly; if a cursor is rejected, start again without one. resourceUri appears on the first page only.',
|
|
53
53
|
'```',
|
|
54
54
|
].join('\n'),
|
|
55
55
|
error_recovery: [
|
|
56
56
|
'Error Recovery:',
|
|
57
57
|
'```',
|
|
58
|
-
`ACCESS_DENIED: Run ${
|
|
59
|
-
`NOT_FOUND: Run ${LIST.name} or ${
|
|
60
|
-
`TOO_LARGE: Use ${
|
|
58
|
+
`ACCESS_DENIED: Run ${LIST_ROOTS.name}; configure a missing startup root or retry a concrete path and approve the grant.`,
|
|
59
|
+
`NOT_FOUND: Run ${LIST.name} or ${FIND_FILES.name} to verify the path.`,
|
|
60
|
+
`TOO_LARGE: Use ${READ.name} with head/tail or startLine/endLine, or split across several calls.`,
|
|
61
61
|
'TIMEOUT: Reduce scope, depth, or maxResults.',
|
|
62
62
|
'INVALID_INPUT: Re-read the tool schema in tools/list.',
|
|
63
63
|
'```',
|
package/dist/instructions.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instructions.js","sourceRoot":"","sources":["../src/instructions.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,8BAA8B,EAC9B,kBAAkB,EAClB,kBAAkB,GACnB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,
|
|
1
|
+
{"version":3,"file":"instructions.js","sourceRoot":"","sources":["../src/instructions.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,8BAA8B,EAC9B,kBAAkB,EAClB,kBAAkB,GACnB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,UAAU,EACV,IAAI,EACJ,UAAU,EACV,mBAAmB,EACnB,IAAI,EACJ,WAAW,EACX,IAAI,GACL,MAAM,kBAAkB,CAAC;AAE1B,SAAS,kBAAkB,CAAC,QAAiB;IAC3C,MAAM,IAAI,GAAyB;QACjC,CAAC,UAAU,EAAE,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC;QAC3D,CAAC,SAAS,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,WAAW,CAAC,IAAI,CAAC,CAAC;QAC1C,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;KACtB,CAAC;IAEF,4EAA4E;IAC5E,4EAA4E;IAC5E,iCAAiC;IACjC,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,IAAI,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,CAAC,GAAG,mB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AC,IAAI,oFAAoF;YACzH,kBAAkB,IAAI,CAAC,IAAI,OAAO,UAAU,CAAC,IAAI,sBAAsB;YACvE,kBAAkB,IAAI,CAAC,IAAI,sEAAsE;YACjG,8CAA8C;YAC9C,uDAAuD;YACvD,KAAK;SACN,CAAC,IAAI,CAAC,IAAI,CAAC;KACb,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,QAAgC;IAC7D,OAAO,KAAK,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC;AACvD,CAAC","sourcesContent":["import {\n DEFAULT_SEARCH_CONTENT_RESULTS,\n getMaxTextFileSize,\n MAX_SEARCH_RESULTS,\n} from './core/util.js';\nimport {\n FIND_FILES,\n LIST,\n LIST_ROOTS,\n MUTATING_TOOL_NAMES,\n READ,\n SEARCH_TEXT,\n STAT,\n} from './tools/index.js';\n\nfunction buildToolsOverview(readOnly: boolean): string {\n const rows: [string, string[]][] = [\n ['Navigate', [LIST_ROOTS.name, LIST.name, FIND_FILES.name]],\n ['Inspect', [STAT.name, SEARCH_TEXT.name]],\n ['Read', [READ.name]],\n ];\n\n // Under --read-only the mutating tools are never registered, so advertising\n // them here would point the model at tools that are not there. Drop the row\n // rather than emit an empty one.\n if (!readOnly) {\n rows.push(['Write', [...MUTATING_TOOL_NAMES]]);\n }\n\n const rowLines = rows.map(([cat, names]) => `${cat}: ${names.join(', ')}`);\n return `\\`\\`\\`\\n${rowLines.join('\\n')}\\n\\`\\`\\``;\n}\n\nexport const INSTRUCTIONS_URI = 'internal://instructions';\n\n/**\n * The one statement of what this server is and how to approach it. The server's\n * `instructions`, the `get-help` prompt, and the instructions resource all\n * describe the same document, and three hand-maintained paraphrases of it drift\n * against each other and cost the client the same sentence three times.\n */\nexport const INSTRUCTIONS_SUMMARY =\n 'Navigation guide for filesystem-mcp tools and constraints. ' +\n 'Use list_roots to inspect configured or accepted roots, then list/find_files -> stat -> read. Never guess paths.';\n\nexport function buildSectionsRecord(readOnly: boolean): Record<string, string> {\n const maxFileMb = Math.floor(getMaxTextFileSize() / 1024 / 1024);\n return {\n guidelines: [\n 'Guidelines:',\n '```',\n `root_access: ${LIST_ROOTS.name} lists configured or accepted roots; every other tool is scoped to them.`,\n 'modern_root_grants: Modern clients do not automatically send workspace roots. Call a tool with a concrete path and approve its grant when elicitation is available.',\n `path_resolution: Confirm a path with ${LIST.name} or ${FIND_FILES.name} before acting on it.`,\n '```',\n ].join('\\n'),\n tools_overview: [\n 'Tools Overview:',\n buildToolsOverview(readOnly),\n '',\n 'Full schemas, descriptions, and annotations are in `tools/list`.',\n ].join('\\n'),\n constraints: [\n 'Constraints:',\n '```',\n `allowed_roots: Startup roots come from CLI paths, FS_ALLOWED_DIRS, or --allow-cwd; accepted modern grants are additive. Call ${LIST_ROOTS.name} to read the current set.`,\n 'legacy_roots: Legacy clients may additionally seed roots through the deprecated roots/list flow.',\n 'sensitive_paths: Sensitive file paths (.env, *.pem, *id_rsa*) are denied by default.',\n `enforced_limits: max file size ${maxFileMb} MB, file search cap ${MAX_SEARCH_RESULTS} results, content search cap ${DEFAULT_SEARCH_CONTENT_RESULTS} matches.`,\n 'ephemeral_results: When a result carries a resource_link or a resourceUri (in structuredContent or _meta), call resources/read immediately — cached results are ephemeral and expire after ~60 seconds, eviction, or restart.',\n 'pagination: nextCursor appears in the result text and in _meta, backed by a snapshot on the same ~60s clock. Page through promptly; if a cursor is rejected, start again without one. resourceUri appears on the first page only.',\n '```',\n ].join('\\n'),\n error_recovery: [\n 'Error Recovery:',\n '```',\n `ACCESS_DENIED: Run ${LIST_ROOTS.name}; configure a missing startup root or retry a concrete path and approve the grant.`,\n `NOT_FOUND: Run ${LIST.name} or ${FIND_FILES.name} to verify the path.`,\n `TOO_LARGE: Use ${READ.name} with head/tail or startLine/endLine, or split across several calls.`,\n 'TIMEOUT: Reduce scope, depth, or maxResults.',\n 'INVALID_INPUT: Re-read the tool schema in tools/list.',\n '```',\n ].join('\\n'),\n };\n}\n\nexport function renderSections(sections: Record<string, string>): string {\n return `\\n${Object.values(sections).join('\\n\\n')}\\n`;\n}\n"]}
|
package/dist/prompts.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompts.d.ts","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"prompts.d.ts","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAmB,SAAS,EAAE,MAAM,8BAA8B,CAAC;AAS/E,UAAU,mBAAmB;IAC3B,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC;IAC3B,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;CAC7B;AAID,wBAAgB,eAAe,CAAC,IAAI,EAAE,mBAAmB,GAAG,IAAI,CAgD/D"}
|
package/dist/prompts.js
CHANGED
|
@@ -1,26 +1,6 @@
|
|
|
1
1
|
import { completable } from '@modelcontextprotocol/server';
|
|
2
2
|
import * as z from 'zod/v4';
|
|
3
|
-
import { Logger } from './core/observability.js';
|
|
4
3
|
import { buildSectionsRecord, INSTRUCTIONS_SUMMARY, renderSections } from './instructions.js';
|
|
5
|
-
// --- Helpers ---
|
|
6
|
-
function topicArg(topics, description) {
|
|
7
|
-
return completable(
|
|
8
|
-
// No content validation beyond non-empty: the handler resolves a topic by
|
|
9
|
-
// `Object.hasOwn` against a frozen record, so anything unrecognized already
|
|
10
|
-
// falls through to the not-found reply without reaching an interpreter.
|
|
11
|
-
z.string().min(1, { message: 'Topic required' }).describe(description), (value) => {
|
|
12
|
-
const lower = value.toLowerCase();
|
|
13
|
-
return lower ? topics.filter((t) => t.startsWith(lower)) : [...topics];
|
|
14
|
-
});
|
|
15
|
-
}
|
|
16
|
-
function userText(text) {
|
|
17
|
-
const content = {
|
|
18
|
-
type: 'text',
|
|
19
|
-
text,
|
|
20
|
-
annotations: { audience: ['assistant'], priority: 1 },
|
|
21
|
-
};
|
|
22
|
-
return { role: 'user', content };
|
|
23
|
-
}
|
|
24
4
|
// --- Prompt entries ---
|
|
25
5
|
export function registerPrompts(deps) {
|
|
26
6
|
const sections = buildSectionsRecord(deps.readOnly ?? false);
|
|
@@ -30,21 +10,33 @@ export function registerPrompts(deps) {
|
|
|
30
10
|
title: 'Get Help',
|
|
31
11
|
description: INSTRUCTIONS_SUMMARY,
|
|
32
12
|
argsSchema: z.strictObject({
|
|
33
|
-
topic:
|
|
13
|
+
topic: completable(
|
|
14
|
+
// No content validation beyond non-empty: the handler resolves a topic by
|
|
15
|
+
// `Object.hasOwn` against a frozen record, so anything unrecognized already
|
|
16
|
+
// falls through to the not-found reply without reaching an interpreter.
|
|
17
|
+
z
|
|
18
|
+
.string()
|
|
19
|
+
.min(1, { message: 'Topic required' })
|
|
20
|
+
.describe(`Section key to filter instructions (one of: ${topics.join(', ')}); omit to return all instructions.`), (value) => {
|
|
21
|
+
const lower = value.toLowerCase();
|
|
22
|
+
return lower ? topics.filter((t) => t.startsWith(lower)) : [...topics];
|
|
23
|
+
}).optional(),
|
|
34
24
|
}),
|
|
35
25
|
}, ({ topic }) => {
|
|
36
26
|
const lowerTopic = topic?.toLowerCase();
|
|
37
27
|
const section = lowerTopic && Object.hasOwn(sections, lowerTopic) ? sections[lowerTopic] : undefined;
|
|
38
|
-
if (topic && !section) {
|
|
39
|
-
Logger.debug('get-help: unknown topic requested', { topic });
|
|
40
|
-
}
|
|
41
28
|
const text = section ??
|
|
42
29
|
(topic
|
|
43
30
|
? `Section '${topic}' not found. Available: ${topics.join(', ')}\n\n${instructions}`
|
|
44
31
|
: instructions);
|
|
45
32
|
return {
|
|
46
33
|
description: INSTRUCTIONS_SUMMARY,
|
|
47
|
-
messages: [
|
|
34
|
+
messages: [
|
|
35
|
+
{
|
|
36
|
+
role: 'user',
|
|
37
|
+
content: { type: 'text', text, annotations: { audience: ['assistant'], priority: 1 } },
|
|
38
|
+
},
|
|
39
|
+
],
|
|
48
40
|
};
|
|
49
41
|
});
|
|
50
42
|
}
|
package/dist/prompts.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompts.js","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"prompts.js","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAE3D,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAS9F,yBAAyB;AAEzB,MAAM,UAAU,eAAe,CAAC,IAAyB;IACvD,MAAM,QAAQ,GAAG,mBAAmB,CAAC,IAAI,CAAC,QAAQ,IAAI,KAAK,CAAC,CAAC;IAC7D,MAAM,YAAY,GAAG,cAAc,CAAC,QAAQ,CAAC,CAAC;IAC9C,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAErC,IAAI,CAAC,MAAM,CAAC,cAAc,CACxB,UAAU,EACV;QACE,KAAK,EAAE,UAAU;QACjB,WAAW,EAAE,oBAAoB;QACjC,UAAU,EAAE,CAAC,CAAC,YAAY,CAAC;YACzB,KAAK,EAAE,WAAW;YAChB,0EAA0E;YAC1E,4EAA4E;YAC5E,wEAAwE;YACxE,CAAC;iBACE,MAAM,EAAE;iBACR,GAAG,CAAC,CAAC,EAAE,EAAE,OAAO,EAAE,gBAAgB,EAAE,CAAC;iBACrC,QAAQ,CACP,+CAA+C,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,qCAAqC,CACtG,EACH,CAAC,KAAK,EAAE,EAAE;gBACR,MAAM,KAAK,GAAG,KAAK,CAAC,WAAW,EAAE,CAAC;gBAClC,OAAO,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC;YACzE,CAAC,CACF,CAAC,QAAQ,EAAE;SACb,CAAC;KACH,EACD,CAAC,EAAE,KAAK,EAAkC,EAAmB,EAAE;QAC7D,MAAM,UAAU,GAAG,KAAK,EAAE,WAAW,EAAE,CAAC;QACxC,MAAM,OAAO,GACX,UAAU,IAAI,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACvF,MAAM,IAAI,GACR,OAAO;YACP,CAAC,KAAK;gBACJ,CAAC,CAAC,YAAY,KAAK,2BAA2B,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,YAAY,EAAE;gBACpF,CAAC,CAAC,YAAY,CAAC,CAAC;QACpB,OAAO;YACL,WAAW,EAAE,oBAAoB;YACjC,QAAQ,EAAE;gBACR;oBACE,IAAI,EAAE,MAAM;oBACZ,OAAO,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,EAAE,QAAQ,EAAE,CAAC,WAAW,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,EAAE;iBACvF;aACF;SACF,CAAC;IACJ,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { GetPromptResult, McpServer } from '@modelcontextprotocol/server';\nimport { completable } from '@modelcontextprotocol/server';\n\nimport * as z from 'zod/v4';\n\nimport { buildSectionsRecord, INSTRUCTIONS_SUMMARY, renderSections } from './instructions.js';\n\n// --- Types ---\n\ninterface PromptRegistrarDeps {\n readonly server: McpServer;\n readonly readOnly?: boolean;\n}\n\n// --- Prompt entries ---\n\nexport function registerPrompts(deps: PromptRegistrarDeps): void {\n const sections = buildSectionsRecord(deps.readOnly ?? false);\n const instructions = renderSections(sections);\n const topics = Object.keys(sections);\n\n deps.server.registerPrompt(\n 'get-help',\n {\n title: 'Get Help',\n description: INSTRUCTIONS_SUMMARY,\n argsSchema: z.strictObject({\n topic: completable(\n // No content validation beyond non-empty: the handler resolves a topic by\n // `Object.hasOwn` against a frozen record, so anything unrecognized already\n // falls through to the not-found reply without reaching an interpreter.\n z\n .string()\n .min(1, { message: 'Topic required' })\n .describe(\n `Section key to filter instructions (one of: ${topics.join(', ')}); omit to return all instructions.`,\n ),\n (value) => {\n const lower = value.toLowerCase();\n return lower ? topics.filter((t) => t.startsWith(lower)) : [...topics];\n },\n ).optional(),\n }),\n },\n ({ topic }: { topic?: string | undefined }): GetPromptResult => {\n const lowerTopic = topic?.toLowerCase();\n const section =\n lowerTopic && Object.hasOwn(sections, lowerTopic) ? sections[lowerTopic] : undefined;\n const text =\n section ??\n (topic\n ? `Section '${topic}' not found. Available: ${topics.join(', ')}\\n\\n${instructions}`\n : instructions);\n return {\n description: INSTRUCTIONS_SUMMARY,\n messages: [\n {\n role: 'user',\n content: { type: 'text', text, annotations: { audience: ['assistant'], priority: 1 } },\n },\n ],\n };\n },\n );\n}\n"]}
|
package/dist/resources.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CacheHint, McpServer, ReadResourceResult, Resource, Role, ServerContext, ServerNotifier } from '@modelcontextprotocol/server';
|
|
1
|
+
import type { CacheHint, CompleteResourceTemplateCallback, McpServer, ReadResourceResult, Resource, Role, ServerContext, ServerNotifier } from '@modelcontextprotocol/server';
|
|
2
2
|
import type { PathGuard } from './core/path.js';
|
|
3
3
|
import type { ResourceStore } from './core/store.js';
|
|
4
4
|
import { type WatcherRegistry } from './core/watcher-registry.js';
|
|
@@ -60,9 +60,9 @@ interface StaticResourceContract extends BaseResourceContract {
|
|
|
60
60
|
interface TemplateResourceContract extends BaseResourceContract {
|
|
61
61
|
uriTemplate: string;
|
|
62
62
|
uri?: never;
|
|
63
|
-
complete?:
|
|
64
|
-
|
|
65
|
-
}
|
|
63
|
+
complete?: {
|
|
64
|
+
path: CompleteResourceTemplateCallback;
|
|
65
|
+
};
|
|
66
66
|
}
|
|
67
67
|
type ResourceContract = StaticResourceContract | TemplateResourceContract;
|
|
68
68
|
export declare function getResourceContracts(options: ResourceRegistrationOptions): ResourceContract[];
|
package/dist/resources.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resources.d.ts","sourceRoot":"","sources":["../src/resources.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,SAAS,EACT,SAAS,EACT,kBAAkB,EAClB,QAAQ,EAER,IAAI,EACJ,aAAa,EACb,cAAc,EAGf,MAAM,8BAA8B,CAAC;
|
|
1
|
+
{"version":3,"file":"resources.d.ts","sourceRoot":"","sources":["../src/resources.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,SAAS,EACT,gCAAgC,EAChC,SAAS,EACT,kBAAkB,EAClB,QAAQ,EAER,IAAI,EACJ,aAAa,EACb,cAAc,EAGf,MAAM,8BAA8B,CAAC;AA2BtC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAGL,KAAK,eAAe,EACrB,MAAM,4BAA4B,CAAC;AAYpC,MAAM,WAAW,2BAA2B;IAC1C,aAAa,EAAE,aAAa,CAAC;IAC7B,SAAS,EAAE,SAAS,CAAC;IACrB,8FAA8F;IAC9F,QAAQ,EAAE,OAAO,CAAC;IAClB;;;;;OAKG;IACH,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC,+CAA+C;IAC/C,QAAQ,CAAC,EAAE,cAAc,CAAC;IAC1B,qFAAqF;IACrF,GAAG,CAAC,EAAE,QAAQ,GAAG,QAAQ,CAAC;IAC1B;;;;OAIG;IACH,UAAU,CAAC,EAAE,QAAQ,GAAG,SAAS,CAAC;CACnC;AAED,KAAK,qBAAqB,GAAG,IAAI,CAAC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AA8E;AAC9E,UAAU,sBAAuB,SAAQ,oBAAoB;IAC3D,GAAG,EAAE,MAAM,CAAC;IACZ,WAAW,CAAC,EAAE,KAAK,CAAC;IACpB,QAAQ,CAAC,EAAE,KAAK,CAAC;CAClB;AAED,8EAA8E;AAC9E,UAAU,wBAAyB,SAAQ,oBAAoB;IAC7D,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,CAAC,EAAE,KAAK,CAAC;IACZ,QAAQ,CAAC,EAAE;QAAE,IAAI,EAAE,gCAAgC,CAAA;KAAE,CAAC;CACvD;AAED,KAAK,gBAAgB,GAAG,sBAAsB,GAAG,wBAAwB,CAAC;AAqP1E,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,2BAA2B,GAAG,gBAAgB,EAAE,CAM7F;AA4BD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,qBAAqB,GAAG;IAAE,OAAO,IAAI,IAAI,CAAA;CAAE,CAiJlF"}
|
package/dist/resources.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { checkResourceAllowed, ProtocolError, ProtocolErrorCode, ResourceNotFoundError, ResourceTemplate, resourceUrlFromServerUrl,
|
|
1
|
+
import { checkResourceAllowed, ProtocolError, ProtocolErrorCode, ResourceNotFoundError, ResourceTemplate, resourceUrlFromServerUrl, } from '@modelcontextprotocol/server';
|
|
2
2
|
import { ErrorCode, formatUnknownErrorMessage, fsErrorCode, hasErrorShape, isFsError, } from './core/errors.js';
|
|
3
3
|
import { decodeFileUriPath, encodeFileUriPath, extractPath, FILESYSTEM_FILE_URI_TEMPLATE, } from './core/file-uri.js';
|
|
4
4
|
import { GuardedFileSystem } from './core/fs.js';
|
|
@@ -110,14 +110,14 @@ function createFilesystemResource(options) {
|
|
|
110
110
|
],
|
|
111
111
|
};
|
|
112
112
|
},
|
|
113
|
-
|
|
114
|
-
if (variable !== 'path')
|
|
115
|
-
return [];
|
|
113
|
+
complete: {
|
|
116
114
|
// Both ends speak the `{+path}` form (see encodeFileUriPath), not raw OS
|
|
117
115
|
// paths: the partial arriving here is whatever this returned last, so the
|
|
118
116
|
// decode mirrors the encode. An undecodable partial is matched as typed.
|
|
119
|
-
|
|
120
|
-
|
|
117
|
+
path: async (value) => {
|
|
118
|
+
const suggestions = await completer.suggest(decodeFileUriPath(value) ?? value);
|
|
119
|
+
return suggestions.map(encodeFileUriPath);
|
|
120
|
+
},
|
|
121
121
|
},
|
|
122
122
|
subscribe(uri, notify) {
|
|
123
123
|
// Already subscribed on this connection: the watcher is live and the sink
|
|
@@ -285,17 +285,7 @@ export function registerResources(deps) {
|
|
|
285
285
|
if (contract.uriTemplate) {
|
|
286
286
|
const template = new ResourceTemplate(contract.uriTemplate, {
|
|
287
287
|
list: contract.list,
|
|
288
|
-
...(contract.complete
|
|
289
|
-
? {
|
|
290
|
-
complete: Object.fromEntries(new UriTemplate(contract.uriTemplate).variableNames.map((varName) => [
|
|
291
|
-
varName,
|
|
292
|
-
(value, ctx) => {
|
|
293
|
-
const completeFn = contract.complete;
|
|
294
|
-
return completeFn ? completeFn(varName, value, ctx) : [];
|
|
295
|
-
},
|
|
296
|
-
])),
|
|
297
|
-
}
|
|
298
|
-
: {}),
|
|
288
|
+
...(contract.complete ? { complete: contract.complete } : {}),
|
|
299
289
|
});
|
|
300
290
|
server.registerResource(contract.name, template, config, wrapRead(contract));
|
|
301
291
|
}
|
package/dist/resources.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resources.js","sourceRoot":"","sources":["../src/resources.ts"],"names":[],"mappings":"AAYA,OAAO,EACL,oBAAoB,EACpB,aAAa,EACb,iBAAiB,EACjB,qBAAqB,EACrB,gBAAgB,EAChB,wBAAwB,EACxB,WAAW,GACZ,MAAM,8BAA8B,CAAC;AAGtC,OAAO,EACL,SAAS,EACT,yBAAyB,EACzB,WAAW,EACX,aAAa,EACb,SAAS,GACV,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EAC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I,CAAC,QAAQ,CAAC,WAAW;oBAAE,SAAS;gBACpC,MAAM,UAAU,GAAG,QAAQ,CAAC,GAAG,IAAI,QAAQ,CAAC,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;gBACtE,IAAI,CAAC,UAAU;oBAAE,SAAS;gBAC1B,IAAI,oBAAoB,CAAC,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,UAAU,EAAE,CAAC,EAAE,CAAC;oBAChF,QAAQ,CAAC,WAAW,CAAC,iBAAiB,CAAC,QAAQ,EAAE,CAAC,CAAC;gBACrD,CAAC;YACH,CAAC;YACD,OAAO,EAAE,CAAC;QACZ,CAAC,CACF,CAAC;IACJ,CAAC;IAED,OAAO;QACL,OAAO;YACL,KAAK,MAAM,QAAQ,IAAI,iBAAiB,EAAE,CAAC;gBACzC,IAAI,QAAQ,CAAC,OAAO,EAAE,CAAC;oBACrB,QAAQ,CAAC,OAAO,EAAE,CAAC;gBACrB,CAAC;YACH,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n CacheHint,\n McpServer,\n ReadResourceResult,\n Resource,\n ResourceUpdatedNotificationParams,\n Role,\n ServerContext,\n ServerNotifier,\n SubscribeRequestParams,\n UnsubscribeRequestParams,\n} from '@modelcontextprotocol/server';\nimport {\n checkResourceAllowed,\n ProtocolError,\n ProtocolErrorCode,\n ResourceNotFoundError,\n ResourceTemplate,\n resourceUrlFromServerUrl,\n UriTemplate,\n} from '@modelcontextprotocol/server';\n\nimport type { FsError } from './core/errors.js';\nimport {\n ErrorCode,\n formatUnknownErrorMessage,\n fsErrorCode,\n hasErrorShape,\n isFsError,\n} from './core/errors.js';\nimport {\n decodeFileUriPath,\n encodeFileUriPath,\n extractPath,\n FILESYSTEM_FILE_URI_TEMPLATE,\n} from './core/file-uri.js';\nimport { GuardedFileSystem } from './core/fs.js';\nimport { Logger } from './core/observability.js';\nimport { PathCompleter } from './core/path-completer.js';\nimport type { PathGuard } from './core/path.js';\nimport type { ResourceStore } from './core/store.js';\nimport {\n createWatcherRegistry,\n MAX_WATCHERS,\n type WatcherRegistry,\n} from './core/watcher-registry.js';\nimport {\n buildSectionsRecord,\n INSTRUCTIONS_SUMMARY,\n INSTRUCTIONS_URI,\n renderSections,\n} from './instructions.js';\n\n// ═══════════════════════════════════════════════════════════════\n// shared\n// ═══════════════════════════════════════════════════════════════\n\nexport interface ResourceRegistrationOptions {\n resourceStore: ResourceStore;\n pathGuard: PathGuard;\n /** Mirrors the `--read-only` gate so the instructions match the tools actually registered. */\n readOnly: boolean;\n /**\n * Shared file-watcher registry for the modern (per-request) HTTP leg. When set,\n * the resource uses this handler-scoped registry instead of creating its own\n * per-server one, so file-change watchers persist across requests and publish\n * to the shared ServerEventBus. Omitted (per-server registry) on legacy/stdio.\n */\n watcherRegistry?: WatcherRegistry;\n /** Modern-leg typed notification publisher. */\n notifier?: ServerNotifier;\n /** The protocol era this instance serves; omitted where the caller does not know. */\n era?: 'legacy' | 'modern';\n /**\n * Scope for shared-content cache hints. 'private' when the endpoint is\n * API-key gated, mirroring the list hints in server.ts — a shared cache must\n * not store an authenticated response body. Defaults to 'public'.\n */\n cacheScope?: 'public' | 'private';\n}\n\ntype ResourceRegistrarDeps = Omit<ResourceRegistrationOptions, 'pathGuard' | 'readOnly'> & {\n readonly server: McpServer;\n readonly pathGuard: PathGuard;\n readonly readOnly?: boolean;\n};\n\n/**\n * A filesystem failure that reads as not-found on the resource wire, for both\n * `resources/read` and `resources/subscribe`. ACCESS_DENIED folds in\n * deliberately: masking whether an out-of-root or denylisted path exists is the\n * security-correct answer, and the `FsError` message still carries the real\n * cause to the client.\n */\nfunction isNotFoundish(error: unknown): error is FsError {\n return (\n isFsError(error) &&\n (error.code === ErrorCode.NOT_FOUND || error.code === ErrorCode.ACCESS_DENIED)\n );\n}\n\n// ═══════════════════════════════════════════════════════════════\n// contract\n// ═══════════════════════════════════════════════════════════════\n\ninterface BaseResourceContract {\n name: string;\n title?: string;\n description?: string;\n mimeType?: string;\n cacheHint?: CacheHint;\n annotations?: {\n audience?: Role[];\n priority?: number;\n };\n readonly read: (\n uri: URL,\n variables: Record<string, string | string[]>,\n ctx: ServerContext,\n ) => Promise<ReadResourceResult> | ReadResourceResult;\n readonly subscribe?: (\n uri: string,\n notify: (uri: string) => void,\n ) => Promise<boolean | undefined> | boolean | undefined;\n readonly unsubscribe?: (uri: string) => void;\n readonly destroy?: () => void;\n readonly list?: (\n ctx: ServerContext,\n ) => Promise<{ resources: Resource[] }> | { resources: Resource[] };\n}\n\n/** A resource with a fixed, enumerable URI (e.g. internal://instructions). */\ninterface StaticResourceContract extends BaseResourceContract {\n uri: string;\n uriTemplate?: never;\n complete?: never;\n}\n\n/** A resource identified by a URI template (FILESYSTEM_FILE_URI_TEMPLATE). */\ninterface TemplateResourceContract extends BaseResourceContract {\n uriTemplate: string;\n uri?: never;\n complete?: (\n variable: string,\n value: string,\n ctx?: { arguments?: Record<string, string> },\n ) => Promise<string[]> | string[];\n}\n\ntype ResourceContract = StaticResourceContract | TemplateResourceContract;\n\n// ═══════════════════════════════════════════════════════════════\n// instructions\n// ═══════════════════════════════════════════════════════════════\n\nfunction createInstructionsResource(options: ResourceRegistrationOptions): ResourceContract {\n const text = renderSections(buildSectionsRecord(options.readOnly));\n return {\n name: 'filesystem-mcp-instructions',\n title: 'Server Instructions',\n description: INSTRUCTIONS_SUMMARY,\n mimeType: 'text/markdown',\n uri: INSTRUCTIONS_URI,\n annotations: { audience: ['assistant'], priority: 0.8 },\n cacheHint: { cacheScope: options.cacheScope ?? 'public', ttlMs: 300_000 },\n read(uri) {\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'text/markdown',\n text,\n },\n ],\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════\n// filesystem\n// ═══════════════════════════════════════════════════════════════\n\nfunction createFilesystemResource(options: ResourceRegistrationOptions): ResourceContract {\n const completer = new PathCompleter(options.pathGuard);\n const registry = options.watcherRegistry ?? createWatcherRegistry();\n // Only the per-server (legacy/stdio) registry is owned by this resource and\n // destroyed on dispose; the shared modern-leg registry is owned by the host\n // and torn down at server shutdown.\n const ownsRegistry = options.watcherRegistry === undefined;\n // The URIs this connection holds a `resources/subscribe` lease for. The wire\n // verb is per-URI and idempotent — a second subscribe is the same\n // subscription, and one unsubscribe ends it — but the registry ref-counts\n // leases (the HTTP listen leg needs that). Without this set a double\n // subscribe took two leases that one unsubscribe could not release, and an\n // unsubscribe for a URI never subscribed released a lease this connection\n // never took, dropping a watcher some other holder still wanted.\n const leasedUris = new Set<string>();\n // Subscribes mid-acquire, keyed by URI. Two concurrent subscribes for the\n // same URI must share one acquire: both passing the `leasedUris` check\n // before either finished took two registry leases that the single set entry\n // could release only once — on the shared modern registry that orphan lease\n // pinned a watcher until process shutdown.\n const inflight = new Map<string, Promise<boolean | undefined>>();\n\n return {\n name: 'filesystem-mcp-file',\n title: 'Workspace File',\n description: 'Read a file from the workspace. Subscribe to get updates when the file changes.',\n uriTemplate: FILESYSTEM_FILE_URI_TEMPLATE,\n annotations: { audience: ['assistant'], priority: 0.8 },\n // Without this the SDK falls back to its conservative `{ ttlMs: 0,\n // cacheScope: 'private' }`, making every file read uncacheable — and this\n // is the one resource with a live invalidation channel, so TTL and the\n // watcher compose exactly as the spec's caching section describes. The TTL\n // stays short because a non-subscriber gets no invalidation signal at all.\n cacheHint: { cacheScope: options.cacheScope ?? 'public', ttlMs: 5_000 },\n\n // No `list`: the template registers with `list: undefined` — readable but\n // not enumerable. Listing each allowed root as a concrete resource\n // duplicated the template and grew resources/list linearly with roots;\n // `list_roots` owns root discovery.\n\n async read(uri, _variables, _ctx: ServerContext) {\n // Decode via extractPath — the same decoder resources/subscribe uses — so\n // both consumers are symmetric with buildFileResourceUri's encoding. The\n // {+path} template variable arrives still percent-encoded, so validating\n // it directly would treat \"c%3A/proj/a.ts\" as a literal relative path;\n // no fallback to it here, or the two branches would validate different\n // strings. extractPath only fails past the template match on undecodable\n // percent-encoding, which is the caller's malformed URI.\n const rawPath = extractPath(uri.href);\n if (rawPath === undefined) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n 'Malformed file URI: path is not valid percent-encoding',\n );\n }\n await options.pathGuard.validateExistingPath(rawPath);\n const fs = new GuardedFileSystem(options.pathGuard);\n const readResult = await fs.readRaw(rawPath);\n\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: readResult.mimeType || 'application/octet-stream',\n ...(readResult.isBinary\n ? { blob: readResult.content.toString('base64') }\n : { text: readResult.content.toString('utf-8') }),\n },\n ],\n };\n },\n\n async complete(variable, value) {\n if (variable !== 'path') return [];\n // Both ends speak the `{+path}` form (see encodeFileUriPath), not raw OS\n // paths: the partial arriving here is whatever this returned last, so the\n // decode mirrors the encode. An undecodable partial is matched as typed.\n const suggestions = await completer.suggest(decodeFileUriPath(value) ?? value);\n return suggestions.map(encodeFileUriPath);\n },\n\n subscribe(uri, notify) {\n // Already subscribed on this connection: the watcher is live and the sink\n // is registered, so this is a no-op success rather than a second lease.\n if (leasedUris.has(uri)) return undefined;\n // A subscribe for this URI is mid-acquire: share its outcome instead of\n // taking a second lease the lease set cannot represent.\n const pending = inflight.get(uri);\n if (pending) return pending;\n\n const acquire = async (): Promise<boolean | undefined> => {\n const result = await registry.acquire(options.pathGuard, uri, notify, {\n markSubscribe: true,\n });\n if (result.ok) {\n leasedUris.add(uri);\n return undefined;\n }\n\n if (result.reason === 'bad-uri') {\n throw new ResourceNotFoundError(uri, `Cannot subscribe: not a filesystem URI`);\n }\n if (result.reason === 'invalid-path') {\n const err = result.error;\n if (isNotFoundish(err)) {\n throw new ResourceNotFoundError(uri, `Cannot subscribe to ${uri}: ${err.message}`);\n }\n Logger.warn(\n `Unexpected error validating path for watcher ${uri}: ${formatUnknownErrorMessage(err)}`,\n );\n throw err;\n }\n // Unsubscribed (or the registry destroyed) mid-await: the caller already\n // asked for this to stop, so there is nothing to reject.\n if (result.reason === 'stale') return undefined;\n // capped / attach-failed: `false` tells the handler to reject, since\n // undefined would report success with no watcher attached.\n return false;\n };\n\n const promise = acquire().finally(() => inflight.delete(uri));\n inflight.set(uri, promise);\n return promise;\n },\n\n unsubscribe(uri) {\n // Only release a lease this connection actually took.\n if (!leasedUris.delete(uri)) return;\n registry.release(uri);\n },\n\n destroy() {\n // Release what this connection still holds before the registry goes: on\n // the shared (modern) registry nothing else would ever end these leases.\n for (const uri of leasedUris) registry.release(uri);\n leasedUris.clear();\n if (ownsRegistry) registry.destroy();\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════\n// result\n// ═══════════════════════════════════════════════════════════════\n\nfunction createResultResource(options: ResourceRegistrationOptions): ResourceContract {\n return {\n name: 'filesystem-mcp-result',\n title: 'Cached Tool Result',\n description:\n 'Ephemeral cached tool output. Listed via resources/list; entries expire after the cache TTL.',\n mimeType: 'application/json',\n uriTemplate: 'filesystem-mcp://result/{id}',\n annotations: { audience: ['assistant'], priority: 0.3 },\n cacheHint: { cacheScope: 'private', ttlMs: 60_000 },\n list() {\n const store = options.resourceStore;\n const uris = store.keys(); // prunes expired first\n const resources: Resource[] = [];\n for (const uri of uris) {\n try {\n const entry = store.getEntry(uri);\n resources.push({\n uri: entry.uri,\n name: entry.name,\n mimeType: entry.mimeType,\n size: entry.size,\n });\n } catch (err) {\n // An entry may expire between keys() and getEntry; skip it.\n if (isFsError(err) && err.code === ErrorCode.NOT_FOUND) continue;\n throw err;\n }\n }\n // Recent-first: keys() returns insertion order, so the newest is last.\n resources.reverse();\n return { resources };\n },\n read(uri, variables) {\n const { id } = variables;\n if (typeof id !== 'string' || id.length === 0) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n 'Malformed result URI: missing {id}. Use the exact resourceUri returned by the tool.',\n );\n }\n\n let entry;\n try {\n entry = options.resourceStore.getEntry(uri.toString());\n } catch (err) {\n if (isFsError(err) && err.code === ErrorCode.NOT_FOUND) {\n throw new ResourceNotFoundError(\n uri.toString(),\n 'Cached result not found or expired. Re-run the tool to regenerate.',\n );\n }\n throw err;\n }\n return {\n contents: [{ uri: entry.uri, mimeType: entry.mimeType, text: entry.text }],\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════\n// export contracts\n// ═══════════════════════════════════════════════════════════════\n\nexport function getResourceContracts(options: ResourceRegistrationOptions): ResourceContract[] {\n return [\n createInstructionsResource(options),\n createResultResource(options),\n createFilesystemResource(options),\n ];\n}\n\n// ═══════════════════════════════════════════════════════════════\n// registrar\n// ═══════════════════════════════════════════════════════════════\n\nfunction wrapRead(contract: ResourceContract) {\n return async (uri: URL, variables: Record<string, string | string[]>, ctx: ServerContext) => {\n try {\n return await contract.read(uri, variables, ctx);\n } catch (error) {\n if (hasErrorShape(error, 'ProtocolError')) throw error;\n // A missing or out-of-root path is a not-found, not a malformed request.\n // The SDK puts ResourceNotFoundError on the wire as -32602 with\n // `data.uri`, which is what clients match on; -32002 is the older code\n // they also accept, and this SDK never emits it.\n if (isNotFoundish(error)) {\n throw new ResourceNotFoundError(uri.toString(), error.message);\n }\n // A remaining FsError (NOT_FILE, TOO_LARGE, ...) traces to the\n // caller-supplied URI; anything else is a server-side failure and must\n // not be blamed on the request.\n const msg = isFsError(error) ? error.message : formatUnknownErrorMessage(error);\n throw new ProtocolError(fsErrorCode(error), msg);\n }\n };\n}\n\nexport function registerResources(deps: ResourceRegistrarDeps): { dispose(): void } {\n const server = deps.server;\n const resourceContracts = getResourceContracts({ ...deps, readOnly: deps.readOnly ?? false });\n\n for (const contract of resourceContracts) {\n const config = {\n ...(contract.title !== undefined ? { title: contract.title } : {}),\n ...(contract.description !== undefined ? { description: contract.description } : {}),\n ...(contract.mimeType !== undefined ? { mimeType: contract.mimeType } : {}),\n ...(contract.annotations !== undefined ? { annotations: contract.annotations } : {}),\n ...(contract.cacheHint !== undefined ? { cacheHint: contract.cacheHint } : {}),\n };\n\n if (contract.uriTemplate) {\n const template = new ResourceTemplate(contract.uriTemplate, {\n list: contract.list,\n ...(contract.complete\n ? {\n complete: Object.fromEntries(\n new UriTemplate(contract.uriTemplate).variableNames.map((varName) => [\n varName,\n (value: string, ctx?: { arguments?: Record<string, string> }) => {\n const completeFn = contract.complete;\n return completeFn ? completeFn(varName, value, ctx) : [];\n },\n ]),\n ),\n }\n : {}),\n });\n\n server.registerResource(contract.name, template, config, wrapRead(contract));\n } else if (contract.uri) {\n server.registerResource(contract.name, contract.uri, config, (uri: URL, ctx: ServerContext) =>\n wrapRead(contract)(uri, {}, ctx),\n );\n }\n }\n\n // `resources/subscribe`/`unsubscribe` are 2025-era-only verbs; a modern\n // server answers `-32601 Method not found` for them, so registering these\n // handlers on a modern-era instance would dispatch to code no request can\n // reach.\n if (deps.era !== 'modern') {\n server.server.assertCanSetRequestHandler('resources/subscribe');\n server.server.assertCanSetRequestHandler('resources/unsubscribe');\n\n // One stable callback for the whole registrar, NOT one per subscribe. The\n // registry holds these in a Set keyed by identity, so a fresh closure per\n // request made a second `resources/subscribe` for the same URI register a\n // second sink: one file change then sent N notifications, and `unsubscribe`\n // (which only ends a lease) removed none of them. Subscribe is per-URI on\n // the wire, so the sink must be too — this makes it idempotent.\n const notifyUpdated = (updatedUri: string): void => {\n if (deps.notifier) {\n deps.notifier.resourceUpdated(updatedUri);\n return;\n }\n const updatePayload: ResourceUpdatedNotificationParams = { uri: updatedUri };\n // A failed notify means the connection went away; nothing to recover.\n void server.server.sendResourceUpdated(updatePayload).catch((err: unknown) => {\n Logger.debug('resource update not delivered', {\n uri: updatedUri,\n error: formatUnknownErrorMessage(err),\n });\n });\n };\n\n server.server.setRequestHandler(\n 'resources/subscribe',\n async (req: { params: SubscribeRequestParams }) => {\n const requestedResource = resourceUrlFromServerUrl(req.params.uri);\n let foundMatch = false;\n // A resource that exists but has no watcher (the instructions text, a\n // cached result) is NOT a not-found: reporting it as one told clients a\n // URI they can list and read does not exist. Track the two cases apart.\n let knownButNotSubscribable = false;\n for (const contract of resourceContracts) {\n const configured = contract.uri ?? contract.uriTemplate.split('{')[0];\n if (!contract.subscribe) {\n if (\n configured &&\n checkResourceAllowed({ requestedResource, configuredResource: configured })\n ) {\n knownButNotSubscribable = true;\n }\n continue;\n }\n if (!configured) continue;\n if (\n checkResourceAllowed({\n requestedResource,\n configuredResource: configured,\n })\n ) {\n foundMatch = true;\n const subscribeResult = await contract.subscribe(\n requestedResource.toString(),\n notifyUpdated,\n );\n if (subscribeResult === false) {\n // InternalError for want of anything better: ProtocolErrorCode\n // has no resource-limit member, and the message already names\n // the actionable cause.\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n `Subscription rejected: no watcher attached (watcher limit ${MAX_WATCHERS} reached, or fs.watch failed to start).`,\n );\n }\n break;\n }\n }\n if (!foundMatch) {\n if (knownButNotSubscribable) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Resource ${requestedResource.toString()} does not support subscriptions; only ${FILESYSTEM_FILE_URI_TEMPLATE} does. Read it again for the current contents.`,\n );\n }\n throw new ResourceNotFoundError(\n requestedResource.toString(),\n `Resource not found: ${requestedResource.toString()}`,\n );\n }\n return {};\n },\n );\n\n server.server.setRequestHandler(\n 'resources/unsubscribe',\n (req: { params: UnsubscribeRequestParams }) => {\n // Route by URI prefix, mirroring the subscribe handler: a broadcast\n // to every contract works while only one is subscribable, but hands a\n // second subscribable contract someone else's URI the day it appears.\n const requestedResource = resourceUrlFromServerUrl(req.params.uri);\n for (const contract of resourceContracts) {\n if (!contract.unsubscribe) continue;\n const configured = contract.uri ?? contract.uriTemplate.split('{')[0];\n if (!configured) continue;\n if (checkResourceAllowed({ requestedResource, configuredResource: configured })) {\n contract.unsubscribe(requestedResource.toString());\n }\n }\n return {};\n },\n );\n }\n\n return {\n dispose(): void {\n for (const contract of resourceContracts) {\n if (contract.destroy) {\n contract.destroy();\n }\n }\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"resources.js","sourceRoot":"","sources":["../src/resources.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,oBAAoB,EACpB,aAAa,EACb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AAC,UAAU;oBAAE,SAAS;gBAC1B,IAAI,oBAAoB,CAAC,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,UAAU,EAAE,CAAC,EAAE,CAAC;oBAChF,QAAQ,CAAC,WAAW,CAAC,iBAAiB,CAAC,QAAQ,EAAE,CAAC,CAAC;gBACrD,CAAC;YACH,CAAC;YACD,OAAO,EAAE,CAAC;QACZ,CAAC,CACF,CAAC;IACJ,CAAC;IAED,OAAO;QACL,OAAO;YACL,KAAK,MAAM,QAAQ,IAAI,iBAAiB,EAAE,CAAC;gBACzC,IAAI,QAAQ,CAAC,OAAO,EAAE,CAAC;oBACrB,QAAQ,CAAC,OAAO,EAAE,CAAC;gBACrB,CAAC;YACH,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n CacheHint,\n CompleteResourceTemplateCallback,\n McpServer,\n ReadResourceResult,\n Resource,\n ResourceUpdatedNotificationParams,\n Role,\n ServerContext,\n ServerNotifier,\n SubscribeRequestParams,\n UnsubscribeRequestParams,\n} from '@modelcontextprotocol/server';\nimport {\n checkResourceAllowed,\n ProtocolError,\n ProtocolErrorCode,\n ResourceNotFoundError,\n ResourceTemplate,\n resourceUrlFromServerUrl,\n} from '@modelcontextprotocol/server';\n\nimport type { FsError } from './core/errors.js';\nimport {\n ErrorCode,\n formatUnknownErrorMessage,\n fsErrorCode,\n hasErrorShape,\n isFsError,\n} from './core/errors.js';\nimport {\n decodeFileUriPath,\n encodeFileUriPath,\n extractPath,\n FILESYSTEM_FILE_URI_TEMPLATE,\n} from './core/file-uri.js';\nimport { GuardedFileSystem } from './core/fs.js';\nimport { Logger } from './core/observability.js';\nimport { PathCompleter } from './core/path-completer.js';\nimport type { PathGuard } from './core/path.js';\nimport type { ResourceStore } from './core/store.js';\nimport {\n createWatcherRegistry,\n MAX_WATCHERS,\n type WatcherRegistry,\n} from './core/watcher-registry.js';\nimport {\n buildSectionsRecord,\n INSTRUCTIONS_SUMMARY,\n INSTRUCTIONS_URI,\n renderSections,\n} from './instructions.js';\n\n// ═══════════════════════════════════════════════════════════════\n// shared\n// ═══════════════════════════════════════════════════════════════\n\nexport interface ResourceRegistrationOptions {\n resourceStore: ResourceStore;\n pathGuard: PathGuard;\n /** Mirrors the `--read-only` gate so the instructions match the tools actually registered. */\n readOnly: boolean;\n /**\n * Shared file-watcher registry for the modern (per-request) HTTP leg. When set,\n * the resource uses this handler-scoped registry instead of creating its own\n * per-server one, so file-change watchers persist across requests and publish\n * to the shared ServerEventBus. Omitted (per-server registry) on legacy/stdio.\n */\n watcherRegistry?: WatcherRegistry;\n /** Modern-leg typed notification publisher. */\n notifier?: ServerNotifier;\n /** The protocol era this instance serves; omitted where the caller does not know. */\n era?: 'legacy' | 'modern';\n /**\n * Scope for shared-content cache hints. 'private' when the endpoint is\n * API-key gated, mirroring the list hints in server.ts — a shared cache must\n * not store an authenticated response body. Defaults to 'public'.\n */\n cacheScope?: 'public' | 'private';\n}\n\ntype ResourceRegistrarDeps = Omit<ResourceRegistrationOptions, 'pathGuard' | 'readOnly'> & {\n readonly server: McpServer;\n readonly pathGuard: PathGuard;\n readonly readOnly?: boolean;\n};\n\n/**\n * A filesystem failure that reads as not-found on the resource wire, for both\n * `resources/read` and `resources/subscribe`. ACCESS_DENIED folds in\n * deliberately: masking whether an out-of-root or denylisted path exists is the\n * security-correct answer, and the `FsError` message still carries the real\n * cause to the client.\n */\nfunction isNotFoundish(error: unknown): error is FsError {\n return (\n isFsError(error) &&\n (error.code === ErrorCode.NOT_FOUND || error.code === ErrorCode.ACCESS_DENIED)\n );\n}\n\n// ═══════════════════════════════════════════════════════════════\n// contract\n// ═══════════════════════════════════════════════════════════════\n\ninterface BaseResourceContract {\n name: string;\n title?: string;\n description?: string;\n mimeType?: string;\n cacheHint?: CacheHint;\n annotations?: {\n audience?: Role[];\n priority?: number;\n };\n readonly read: (\n uri: URL,\n variables: Record<string, string | string[]>,\n ctx: ServerContext,\n ) => Promise<ReadResourceResult> | ReadResourceResult;\n readonly subscribe?: (\n uri: string,\n notify: (uri: string) => void,\n ) => Promise<boolean | undefined> | boolean | undefined;\n readonly unsubscribe?: (uri: string) => void;\n readonly destroy?: () => void;\n readonly list?: (\n ctx: ServerContext,\n ) => Promise<{ resources: Resource[] }> | { resources: Resource[] };\n}\n\n/** A resource with a fixed, enumerable URI (e.g. internal://instructions). */\ninterface StaticResourceContract extends BaseResourceContract {\n uri: string;\n uriTemplate?: never;\n complete?: never;\n}\n\n/** A resource identified by a URI template (FILESYSTEM_FILE_URI_TEMPLATE). */\ninterface TemplateResourceContract extends BaseResourceContract {\n uriTemplate: string;\n uri?: never;\n complete?: { path: CompleteResourceTemplateCallback };\n}\n\ntype ResourceContract = StaticResourceContract | TemplateResourceContract;\n\n// ═══════════════════════════════════════════════════════════════\n// instructions\n// ═══════════════════════════════════════════════════════════════\n\nfunction createInstructionsResource(options: ResourceRegistrationOptions): ResourceContract {\n const text = renderSections(buildSectionsRecord(options.readOnly));\n return {\n name: 'filesystem-mcp-instructions',\n title: 'Server Instructions',\n description: INSTRUCTIONS_SUMMARY,\n mimeType: 'text/markdown',\n uri: INSTRUCTIONS_URI,\n annotations: { audience: ['assistant'], priority: 0.8 },\n cacheHint: { cacheScope: options.cacheScope ?? 'public', ttlMs: 300_000 },\n read(uri) {\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'text/markdown',\n text,\n },\n ],\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════\n// filesystem\n// ═══════════════════════════════════════════════════════════════\n\nfunction createFilesystemResource(options: ResourceRegistrationOptions): ResourceContract {\n const completer = new PathCompleter(options.pathGuard);\n const registry = options.watcherRegistry ?? createWatcherRegistry();\n // Only the per-server (legacy/stdio) registry is owned by this resource and\n // destroyed on dispose; the shared modern-leg registry is owned by the host\n // and torn down at server shutdown.\n const ownsRegistry = options.watcherRegistry === undefined;\n // The URIs this connection holds a `resources/subscribe` lease for. The wire\n // verb is per-URI and idempotent — a second subscribe is the same\n // subscription, and one unsubscribe ends it — but the registry ref-counts\n // leases (the HTTP listen leg needs that). Without this set a double\n // subscribe took two leases that one unsubscribe could not release, and an\n // unsubscribe for a URI never subscribed released a lease this connection\n // never took, dropping a watcher some other holder still wanted.\n const leasedUris = new Set<string>();\n // Subscribes mid-acquire, keyed by URI. Two concurrent subscribes for the\n // same URI must share one acquire: both passing the `leasedUris` check\n // before either finished took two registry leases that the single set entry\n // could release only once — on the shared modern registry that orphan lease\n // pinned a watcher until process shutdown.\n const inflight = new Map<string, Promise<boolean | undefined>>();\n\n return {\n name: 'filesystem-mcp-file',\n title: 'Workspace File',\n description: 'Read a file from the workspace. Subscribe to get updates when the file changes.',\n uriTemplate: FILESYSTEM_FILE_URI_TEMPLATE,\n annotations: { audience: ['assistant'], priority: 0.8 },\n // Without this the SDK falls back to its conservative `{ ttlMs: 0,\n // cacheScope: 'private' }`, making every file read uncacheable — and this\n // is the one resource with a live invalidation channel, so TTL and the\n // watcher compose exactly as the spec's caching section describes. The TTL\n // stays short because a non-subscriber gets no invalidation signal at all.\n cacheHint: { cacheScope: options.cacheScope ?? 'public', ttlMs: 5_000 },\n\n // No `list`: the template registers with `list: undefined` — readable but\n // not enumerable. Listing each allowed root as a concrete resource\n // duplicated the template and grew resources/list linearly with roots;\n // `list_roots` owns root discovery.\n\n async read(uri, _variables, _ctx: ServerContext) {\n // Decode via extractPath — the same decoder resources/subscribe uses — so\n // both consumers are symmetric with buildFileResourceUri's encoding. The\n // {+path} template variable arrives still percent-encoded, so validating\n // it directly would treat \"c%3A/proj/a.ts\" as a literal relative path;\n // no fallback to it here, or the two branches would validate different\n // strings. extractPath only fails past the template match on undecodable\n // percent-encoding, which is the caller's malformed URI.\n const rawPath = extractPath(uri.href);\n if (rawPath === undefined) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n 'Malformed file URI: path is not valid percent-encoding',\n );\n }\n await options.pathGuard.validateExistingPath(rawPath);\n const fs = new GuardedFileSystem(options.pathGuard);\n const readResult = await fs.readRaw(rawPath);\n\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: readResult.mimeType || 'application/octet-stream',\n ...(readResult.isBinary\n ? { blob: readResult.content.toString('base64') }\n : { text: readResult.content.toString('utf-8') }),\n },\n ],\n };\n },\n\n complete: {\n // Both ends speak the `{+path}` form (see encodeFileUriPath), not raw OS\n // paths: the partial arriving here is whatever this returned last, so the\n // decode mirrors the encode. An undecodable partial is matched as typed.\n path: async (value) => {\n const suggestions = await completer.suggest(decodeFileUriPath(value) ?? value);\n return suggestions.map(encodeFileUriPath);\n },\n },\n\n subscribe(uri, notify) {\n // Already subscribed on this connection: the watcher is live and the sink\n // is registered, so this is a no-op success rather than a second lease.\n if (leasedUris.has(uri)) return undefined;\n // A subscribe for this URI is mid-acquire: share its outcome instead of\n // taking a second lease the lease set cannot represent.\n const pending = inflight.get(uri);\n if (pending) return pending;\n\n const acquire = async (): Promise<boolean | undefined> => {\n const result = await registry.acquire(options.pathGuard, uri, notify, {\n markSubscribe: true,\n });\n if (result.ok) {\n leasedUris.add(uri);\n return undefined;\n }\n\n if (result.reason === 'bad-uri') {\n throw new ResourceNotFoundError(uri, `Cannot subscribe: not a filesystem URI`);\n }\n if (result.reason === 'invalid-path') {\n const err = result.error;\n if (isNotFoundish(err)) {\n throw new ResourceNotFoundError(uri, `Cannot subscribe to ${uri}: ${err.message}`);\n }\n Logger.warn(\n `Unexpected error validating path for watcher ${uri}: ${formatUnknownErrorMessage(err)}`,\n );\n throw err;\n }\n // Unsubscribed (or the registry destroyed) mid-await: the caller already\n // asked for this to stop, so there is nothing to reject.\n if (result.reason === 'stale') return undefined;\n // capped / attach-failed: `false` tells the handler to reject, since\n // undefined would report success with no watcher attached.\n return false;\n };\n\n const promise = acquire().finally(() => inflight.delete(uri));\n inflight.set(uri, promise);\n return promise;\n },\n\n unsubscribe(uri) {\n // Only release a lease this connection actually took.\n if (!leasedUris.delete(uri)) return;\n registry.release(uri);\n },\n\n destroy() {\n // Release what this connection still holds before the registry goes: on\n // the shared (modern) registry nothing else would ever end these leases.\n for (const uri of leasedUris) registry.release(uri);\n leasedUris.clear();\n if (ownsRegistry) registry.destroy();\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════\n// result\n// ═══════════════════════════════════════════════════════════════\n\nfunction createResultResource(options: ResourceRegistrationOptions): ResourceContract {\n return {\n name: 'filesystem-mcp-result',\n title: 'Cached Tool Result',\n description:\n 'Ephemeral cached tool output. Listed via resources/list; entries expire after the cache TTL.',\n mimeType: 'application/json',\n uriTemplate: 'filesystem-mcp://result/{id}',\n annotations: { audience: ['assistant'], priority: 0.3 },\n cacheHint: { cacheScope: 'private', ttlMs: 60_000 },\n list() {\n const store = options.resourceStore;\n const uris = store.keys(); // prunes expired first\n const resources: Resource[] = [];\n for (const uri of uris) {\n try {\n const entry = store.getEntry(uri);\n resources.push({\n uri: entry.uri,\n name: entry.name,\n mimeType: entry.mimeType,\n size: entry.size,\n });\n } catch (err) {\n // An entry may expire between keys() and getEntry; skip it.\n if (isFsError(err) && err.code === ErrorCode.NOT_FOUND) continue;\n throw err;\n }\n }\n // Recent-first: keys() returns insertion order, so the newest is last.\n resources.reverse();\n return { resources };\n },\n read(uri, variables) {\n const { id } = variables;\n if (typeof id !== 'string' || id.length === 0) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n 'Malformed result URI: missing {id}. Use the exact resourceUri returned by the tool.',\n );\n }\n\n let entry;\n try {\n entry = options.resourceStore.getEntry(uri.toString());\n } catch (err) {\n if (isFsError(err) && err.code === ErrorCode.NOT_FOUND) {\n throw new ResourceNotFoundError(\n uri.toString(),\n 'Cached result not found or expired. Re-run the tool to regenerate.',\n );\n }\n throw err;\n }\n return {\n contents: [{ uri: entry.uri, mimeType: entry.mimeType, text: entry.text }],\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════\n// export contracts\n// ═══════════════════════════════════════════════════════════════\n\nexport function getResourceContracts(options: ResourceRegistrationOptions): ResourceContract[] {\n return [\n createInstructionsResource(options),\n createResultResource(options),\n createFilesystemResource(options),\n ];\n}\n\n// ═══════════════════════════════════════════════════════════════\n// registrar\n// ═══════════════════════════════════════════════════════════════\n\nfunction wrapRead(contract: ResourceContract) {\n return async (uri: URL, variables: Record<string, string | string[]>, ctx: ServerContext) => {\n try {\n return await contract.read(uri, variables, ctx);\n } catch (error) {\n if (hasErrorShape(error, 'ProtocolError')) throw error;\n // A missing or out-of-root path is a not-found, not a malformed request.\n // The SDK puts ResourceNotFoundError on the wire as -32602 with\n // `data.uri`, which is what clients match on; -32002 is the older code\n // they also accept, and this SDK never emits it.\n if (isNotFoundish(error)) {\n throw new ResourceNotFoundError(uri.toString(), error.message);\n }\n // A remaining FsError (NOT_FILE, TOO_LARGE, ...) traces to the\n // caller-supplied URI; anything else is a server-side failure and must\n // not be blamed on the request.\n const msg = isFsError(error) ? error.message : formatUnknownErrorMessage(error);\n throw new ProtocolError(fsErrorCode(error), msg);\n }\n };\n}\n\nexport function registerResources(deps: ResourceRegistrarDeps): { dispose(): void } {\n const server = deps.server;\n const resourceContracts = getResourceContracts({ ...deps, readOnly: deps.readOnly ?? false });\n\n for (const contract of resourceContracts) {\n const config = {\n ...(contract.title !== undefined ? { title: contract.title } : {}),\n ...(contract.description !== undefined ? { description: contract.description } : {}),\n ...(contract.mimeType !== undefined ? { mimeType: contract.mimeType } : {}),\n ...(contract.annotations !== undefined ? { annotations: contract.annotations } : {}),\n ...(contract.cacheHint !== undefined ? { cacheHint: contract.cacheHint } : {}),\n };\n\n if (contract.uriTemplate) {\n const template = new ResourceTemplate(contract.uriTemplate, {\n list: contract.list,\n ...(contract.complete ? { complete: contract.complete } : {}),\n });\n\n server.registerResource(contract.name, template, config, wrapRead(contract));\n } else if (contract.uri) {\n server.registerResource(contract.name, contract.uri, config, (uri: URL, ctx: ServerContext) =>\n wrapRead(contract)(uri, {}, ctx),\n );\n }\n }\n\n // `resources/subscribe`/`unsubscribe` are 2025-era-only verbs; a modern\n // server answers `-32601 Method not found` for them, so registering these\n // handlers on a modern-era instance would dispatch to code no request can\n // reach.\n if (deps.era !== 'modern') {\n server.server.assertCanSetRequestHandler('resources/subscribe');\n server.server.assertCanSetRequestHandler('resources/unsubscribe');\n\n // One stable callback for the whole registrar, NOT one per subscribe. The\n // registry holds these in a Set keyed by identity, so a fresh closure per\n // request made a second `resources/subscribe` for the same URI register a\n // second sink: one file change then sent N notifications, and `unsubscribe`\n // (which only ends a lease) removed none of them. Subscribe is per-URI on\n // the wire, so the sink must be too — this makes it idempotent.\n const notifyUpdated = (updatedUri: string): void => {\n if (deps.notifier) {\n deps.notifier.resourceUpdated(updatedUri);\n return;\n }\n const updatePayload: ResourceUpdatedNotificationParams = { uri: updatedUri };\n // A failed notify means the connection went away; nothing to recover.\n void server.server.sendResourceUpdated(updatePayload).catch((err: unknown) => {\n Logger.debug('resource update not delivered', {\n uri: updatedUri,\n error: formatUnknownErrorMessage(err),\n });\n });\n };\n\n server.server.setRequestHandler(\n 'resources/subscribe',\n async (req: { params: SubscribeRequestParams }) => {\n const requestedResource = resourceUrlFromServerUrl(req.params.uri);\n let foundMatch = false;\n // A resource that exists but has no watcher (the instructions text, a\n // cached result) is NOT a not-found: reporting it as one told clients a\n // URI they can list and read does not exist. Track the two cases apart.\n let knownButNotSubscribable = false;\n for (const contract of resourceContracts) {\n const configured = contract.uri ?? contract.uriTemplate.split('{')[0];\n if (!contract.subscribe) {\n if (\n configured &&\n checkResourceAllowed({ requestedResource, configuredResource: configured })\n ) {\n knownButNotSubscribable = true;\n }\n continue;\n }\n if (!configured) continue;\n if (\n checkResourceAllowed({\n requestedResource,\n configuredResource: configured,\n })\n ) {\n foundMatch = true;\n const subscribeResult = await contract.subscribe(\n requestedResource.toString(),\n notifyUpdated,\n );\n if (subscribeResult === false) {\n // InternalError for want of anything better: ProtocolErrorCode\n // has no resource-limit member, and the message already names\n // the actionable cause.\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n `Subscription rejected: no watcher attached (watcher limit ${MAX_WATCHERS} reached, or fs.watch failed to start).`,\n );\n }\n break;\n }\n }\n if (!foundMatch) {\n if (knownButNotSubscribable) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Resource ${requestedResource.toString()} does not support subscriptions; only ${FILESYSTEM_FILE_URI_TEMPLATE} does. Read it again for the current contents.`,\n );\n }\n throw new ResourceNotFoundError(\n requestedResource.toString(),\n `Resource not found: ${requestedResource.toString()}`,\n );\n }\n return {};\n },\n );\n\n server.server.setRequestHandler(\n 'resources/unsubscribe',\n (req: { params: UnsubscribeRequestParams }) => {\n // Route by URI prefix, mirroring the subscribe handler: a broadcast\n // to every contract works while only one is subscribable, but hands a\n // second subscribable contract someone else's URI the day it appears.\n const requestedResource = resourceUrlFromServerUrl(req.params.uri);\n for (const contract of resourceContracts) {\n if (!contract.unsubscribe) continue;\n const configured = contract.uri ?? contract.uriTemplate.split('{')[0];\n if (!configured) continue;\n if (checkResourceAllowed({ requestedResource, configuredResource: configured })) {\n contract.unsubscribe(requestedResource.toString());\n }\n }\n return {};\n },\n );\n }\n\n return {\n dispose(): void {\n for (const contract of resourceContracts) {\n if (contract.destroy) {\n contract.destroy();\n }\n }\n },\n };\n}\n"]}
|