Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

### Fixed

- Read MCP saved-history files through verified descriptors so path swaps cannot expose symbolic-link targets.
- Protect legacy and source-backed user/server memory reads and writes from symbolic links, junctions, and path swaps.
- Require a text response for `!ask` commands even when their prompt is phrased without a question mark.
- Remove malformed `[REACT:]` directives from legacy Claude responses instead of sending them as Discord text.
Expand Down
122 changes: 74 additions & 48 deletions src/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
MCP_FETCH_MESSAGES_MAX_LINKS,
MCP_READ_MESSAGES_MAX_CHARS,
MCP_HISTORY_MAX_CHARS,
MESSAGES_DIR,
PENDING_DIR,
} from "../config.js";
import { client } from "../discord/client.js";
Expand All @@ -28,6 +29,7 @@ import {
isCalendarDate,
} from "./historyFiles.js";
import { parseChannelHistoryFileName } from "../storage/historyPaths.js";
import { readVerifiedUtf8File } from "../storage/safeRead.js";

const ReactToMessageSchema = z.object({
server: z
Expand Down Expand Up @@ -55,12 +57,12 @@ function isWithinDiscordMessageLimit(message: string): boolean {
return true;
}

function readPendingMetadata(filePath: string): {
function readPendingMetadata(text: string): {
channelId: string | undefined;
channelName: string | undefined;
date: string | undefined;
} {
const lines = fs.readFileSync(filePath, "utf-8").split("\n");
const lines = text.split("\n");
const separatorIndex = lines.indexOf("---");
const headerLines = lines.slice(0, separatorIndex === -1 ? 4 : separatorIndex);
const channelLine = headerLines.find((line) => line.startsWith("Channel: #"));
Expand All @@ -86,6 +88,26 @@ function readPendingMetadata(filePath: string): {
};
}

interface ReadableHistoryFile {
displayName: string;
channelId: string | undefined;
channelName: string | undefined;
date: string | undefined;
text: string;
}

function readStoredHistoryFile(
filePath: string,
expectedDirectory: string,
): string | undefined {
const result = readVerifiedUtf8File(
filePath,
MESSAGES_DIR,
expectedDirectory,
);
return result.state === "valid" ? result.text : undefined;
}

const HISTORY_RESPONSE_SEPARATOR = "\n\n===\n\n";

function takeUtf16Suffix(text: string, maxChars: number): string {
Expand Down Expand Up @@ -496,54 +518,59 @@ export function createMcpServer(): Server {
"_",
)
: undefined;
let files = fs
.readdirSync(dir, { withFileTypes: true })
.filter(
(entry) =>
entry.isFile() && entry.name.endsWith(".txt"),
)
.map((entry) => {
const filePath = path.join(dir, entry.name);
const pendingMetadata =
type === "pending"
? readPendingMetadata(filePath)
: undefined;
return {
displayName: entry.name,
filePath,
channelId: pendingMetadata?.channelId,
channelName:
type === "history"
? getLegacyHistoryChannel(entry.name)
: pendingMetadata?.channelName,
date: pendingMetadata?.date,
};
let files: ReadableHistoryFile[] = [];
for (const entry of fs.readdirSync(dir, {
withFileTypes: true,
})) {
if (!entry.isFile() || !entry.name.endsWith(".txt")) {
continue;
}
const filePath = path.join(dir, entry.name);
const text = readStoredHistoryFile(filePath, dir);
if (text === undefined) continue;
const pendingMetadata = type === "pending"
? readPendingMetadata(text)
: undefined;
files.push({
displayName: entry.name,
channelId: pendingMetadata?.channelId,
channelName:
type === "history"
? getLegacyHistoryChannel(entry.name)
: pendingMetadata?.channelName,
date: pendingMetadata?.date,
text,
});
}

if (type === "history") {
const channelFiles = fs
.readdirSync(HISTORY_V2_DIR, { withFileTypes: true })
.filter(
(entry) =>
entry.isFile() &&
entry.name.endsWith(".txt"),
)
.map((entry) => {
const parsed = parseChannelHistoryFileName(
entry.name,
);
return {
displayName: `v2/${entry.name}`,
filePath: path.join(
HISTORY_V2_DIR,
entry.name,
),
channelId: parsed?.channelId,
channelName: parsed?.channelName,
date: undefined,
};
for (const entry of fs.readdirSync(HISTORY_V2_DIR, {
withFileTypes: true,
})) {
if (
!entry.isFile()
|| !entry.name.endsWith(".txt")
) continue;
const filePath = path.join(
HISTORY_V2_DIR,
entry.name,
);
const text = readStoredHistoryFile(
filePath,
HISTORY_V2_DIR,
);
if (text === undefined) continue;
const parsed = parseChannelHistoryFileName(
entry.name,
);
files.push({
displayName: `v2/${entry.name}`,
channelId: parsed?.channelId,
channelName: parsed?.channelName,
date: undefined,
text,
});
files.push(...channelFiles);
}
files.sort((left, right) =>
compareHistoryFilenames(
left.displayName,
Expand Down Expand Up @@ -577,8 +604,7 @@ export function createMcpServer(): Server {
: files.slice(-limit);
let matchingFiles = candidateFiles
.map((file) => {
let lines = fs
.readFileSync(file.filePath, "utf-8")
let lines = file.text
.split("\n")
.filter((line) => line.trim().length > 0);

Expand Down
30 changes: 30 additions & 0 deletions tests/mcpHistory.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@ test("MCP history filters matching regular files and preserves pending indentati
path.join(historyDir, "linked_2026-08-01.txt"),
);
fs.mkdirSync(path.join(historyDir, "directory_2026-08-01.txt"));
const swappedHistoryFile = path.join(
historyDir,
"swapped_2026-08-01.txt",
);
fs.writeFileSync(swappedHistoryFile, "ordinary history entry\n", "utf8");
fs.symlinkSync(
outsideFile,
path.join(
Expand Down Expand Up @@ -124,6 +129,31 @@ test("MCP history filters matching regular files and preserves pending indentati
assert.doesNotMatch(text, /directory_2026-08-01\.txt/);
assert.doesNotMatch(text, /symlinked secret/);

const originalReaddirSync = fs.readdirSync;
fs.readdirSync = function patchedReaddirSync(directory, options) {
const entries = originalReaddirSync.call(fs, directory, options);
if (path.resolve(directory.toString()) === path.resolve(historyDir)) {
fs.rmSync(swappedHistoryFile, { force: true });
fs.symlinkSync(outsideFile, swappedHistoryFile);
}
return entries;
};
let swappedResult;
try {
swappedResult = await client.callTool({
name: "read-message-history",
arguments: { date: "2026-08-01" },
});
} finally {
fs.readdirSync = originalReaddirSync;
}
const swappedText = swappedResult.content.find(
(item) => item.type === "text",
)?.text;
assert.equal(typeof swappedText, "string");
assert.doesNotMatch(swappedText, /swapped_2026-08-01\.txt/);
assert.doesNotMatch(swappedText, /symlinked secret/);

const pendingResult = await client.callTool({
name: "read-message-history",
arguments: { type: "pending" },
Expand Down