m365connector 0.3.4 → 0.3.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "m365connector",
3
- "version": "0.3.4",
3
+ "version": "0.3.6",
4
4
  "description": "MCP server for M365 Connector browser extension",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
package/src/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import crypto from "node:crypto";
2
2
  import fs from "node:fs";
3
+ import os from "node:os";
3
4
  import path from "node:path";
4
5
  import { fileURLToPath, pathToFileURL } from "node:url";
5
6
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
@@ -65,6 +66,126 @@ function createReadHandleCache() {
65
66
  return cache;
66
67
  }
67
68
 
69
+ const TEMP_FILE_TTL_MS = 30 * 60 * 1000;
70
+
71
+ function createTempFileManager(logger) {
72
+ const rootDir = path.join(os.tmpdir(), "m365c-open");
73
+
74
+ // Validate shared root: reject symlinks, non-directories, or foreign-owned dirs
75
+ try {
76
+ const rootStat = fs.lstatSync(rootDir);
77
+ if (rootStat.isSymbolicLink()) {
78
+ fs.unlinkSync(rootDir);
79
+ logger.warn("[m365connector] removed symlink at temp root:", rootDir);
80
+ } else if (rootStat.isFile()) {
81
+ fs.unlinkSync(rootDir);
82
+ logger.warn("[m365connector] removed regular file at temp root:", rootDir);
83
+ } else if (!rootStat.isDirectory()) {
84
+ throw new Error(`Unsafe temp root type at ${rootDir} (not a directory, symlink, or file)`);
85
+ } else {
86
+ // Verify directory ownership on POSIX
87
+ const uid = typeof process.getuid === "function" ? process.getuid() : null;
88
+ if (uid != null && rootStat.uid !== uid) {
89
+ throw new Error(`Unsafe temp root owner at ${rootDir} (owned by uid ${rootStat.uid}, expected ${uid})`);
90
+ }
91
+ }
92
+ } catch (err) {
93
+ if (err.code !== "ENOENT") {
94
+ throw err;
95
+ }
96
+ }
97
+
98
+ // Create shared root for stale file sweeps across processes
99
+ try {
100
+ fs.mkdirSync(rootDir, { recursive: true, mode: 0o700 });
101
+ } catch {
102
+ // Root may be owned by another user; sweep will be skipped below
103
+ }
104
+
105
+ // Sweep stale files/dirs from previous crashed processes on startup
106
+ try {
107
+ for (const entry of fs.readdirSync(rootDir)) {
108
+ const entryPath = path.join(rootDir, entry);
109
+ try {
110
+ const stat = fs.statSync(entryPath);
111
+ if (Date.now() - stat.mtimeMs > TEMP_FILE_TTL_MS) {
112
+ if (stat.isDirectory()) {
113
+ for (const f of fs.readdirSync(entryPath)) {
114
+ try { fs.unlinkSync(path.join(entryPath, f)); } catch {}
115
+ }
116
+ fs.rmdirSync(entryPath);
117
+ } else {
118
+ fs.unlinkSync(entryPath);
119
+ }
120
+ }
121
+ } catch (err) {
122
+ logger.warn("[m365connector] failed to sweep stale temp entry:", entryPath, err.message);
123
+ }
124
+ }
125
+ } catch (err) {
126
+ logger.warn("[m365connector] failed to read temp root for cleanup:", err.message);
127
+ }
128
+
129
+ // Create process-owned subdirectory — immune to pre-creation attacks
130
+ const baseDir = fs.mkdtempSync(path.join(rootDir, "proc-"));
131
+ fs.chmodSync(baseDir, 0o700);
132
+
133
+ const tracked = new Map(); // filePath → expiresAt
134
+
135
+ const interval = setInterval(() => {
136
+ const now = Date.now();
137
+ for (const [filePath, expiresAt] of tracked.entries()) {
138
+ if (expiresAt < now) {
139
+ tracked.delete(filePath);
140
+ fs.unlink(filePath, (err) => {
141
+ if (err && err.code !== "ENOENT") {
142
+ logger.warn("[m365connector] failed to delete temp file:", filePath, err.message);
143
+ }
144
+ });
145
+ }
146
+ }
147
+ }, 60_000);
148
+ interval.unref();
149
+
150
+ function ensureDir() {
151
+ try {
152
+ fs.mkdirSync(baseDir, { recursive: true, mode: 0o700 });
153
+ fs.chmodSync(baseDir, 0o700);
154
+ } catch (err) {
155
+ logger.warn("[m365connector] failed to ensure temp directory:", err.message);
156
+ throw err;
157
+ }
158
+ }
159
+
160
+ return {
161
+ write(content) {
162
+ ensureDir();
163
+ const fileName = `${crypto.randomUUID()}.txt`;
164
+ const filePath = path.join(baseDir, fileName);
165
+ fs.writeFileSync(filePath, content, { encoding: "utf-8", mode: 0o600, flag: "wx" });
166
+ tracked.set(filePath, Date.now() + TEMP_FILE_TTL_MS);
167
+ return filePath;
168
+ },
169
+ cleanup() {
170
+ clearInterval(interval);
171
+ for (const filePath of tracked.keys()) {
172
+ try {
173
+ fs.unlinkSync(filePath);
174
+ } catch (err) {
175
+ if (err.code !== "ENOENT") {
176
+ logger.warn("[m365connector] failed to delete temp file:", filePath, err.message);
177
+ }
178
+ }
179
+ }
180
+ tracked.clear();
181
+ // Remove the per-process directory itself
182
+ try {
183
+ fs.rmdirSync(baseDir);
184
+ } catch {}
185
+ }
186
+ };
187
+ }
188
+
68
189
  async function loadToolModules(toolRegistry, context) {
69
190
  const toolsDir = path.resolve(__dirname, "tools");
70
191
  const files = fs
@@ -171,6 +292,7 @@ async function main() {
171
292
  };
172
293
 
173
294
  const readHandleCache = createReadHandleCache();
295
+ const tempFiles = createTempFileManager(stderrLogger);
174
296
 
175
297
  const ws = new WsServer({
176
298
  host: "127.0.0.1",
@@ -180,7 +302,7 @@ async function main() {
180
302
  await ws.start();
181
303
 
182
304
  const toolRegistry = new ToolRegistry();
183
- const toolContext = { ws, readHandleCache };
305
+ const toolContext = { ws, readHandleCache, tempFiles };
184
306
  await loadToolModules(toolRegistry, toolContext);
185
307
 
186
308
  const sessions = new Map();
@@ -288,6 +410,8 @@ async function main() {
288
410
  stderrLogger.warn("[m365connector] failed to stop WebSocket server:", err);
289
411
  }
290
412
 
413
+ tempFiles.cleanup();
414
+
291
415
  await new Promise((resolve) => {
292
416
  httpServer.close(() => resolve());
293
417
  });
@@ -4,10 +4,13 @@ const WHOAMI_TIMEOUT_MS = 60000;
4
4
  const FIND_PEOPLE_TIMEOUT_MS = 90000;
5
5
  const COUNT_PEOPLE_TIMEOUT_MS = 120000;
6
6
 
7
+ const SEARCH_FILE_THRESHOLD = 8192;
8
+ const OPEN_FILE_THRESHOLD = 4096;
9
+
7
10
  const SEARCH_TOOL = {
8
11
  name: "search",
9
12
  description:
10
- "Search across Microsoft 365 data including emails, files, Teams chats, calendar events, and external connectors.",
13
+ "Search across Microsoft 365 data including emails, files, Teams chats, calendar events, and external connectors. Large result sets are saved to a local temp file — use the returned file_path with your file-reading tool to access the full results.",
11
14
  inputSchema: {
12
15
  type: "object",
13
16
  properties: {
@@ -50,7 +53,7 @@ const SEARCH_TOOL = {
50
53
  const OPEN_TOOL = {
51
54
  name: "open",
52
55
  description:
53
- "Open and read best-effort content for a prior search result using its read handle. Returns completeness metadata: full, partial, or snippet.",
56
+ "Open and read content for a prior search result. Returns a summary with metadata. Small content is returned inline in the 'content' field. Large content is saved to a local temp file — use the returned file_path with your file-reading tool to access the content.",
54
57
  inputSchema: {
55
58
  type: "object",
56
59
  properties: {
@@ -271,7 +274,7 @@ export function registerTools(registry, context) {
271
274
  const readHandle = makeReadHandle(context.readHandleCache, readContext);
272
275
 
273
276
  // Only expose the opaque handle to agents; never return internal read context.
274
- return {
277
+ const entry = {
275
278
  index: Number.isInteger(publicRow.index) ? publicRow.index : index,
276
279
  type: publicRow.type || "",
277
280
  title: publicRow.title || "",
@@ -300,9 +303,18 @@ export function registerTools(registry, context) {
300
303
  email: publicRow.email,
301
304
  _readHandle: readHandle
302
305
  };
306
+
307
+ // Strip null/undefined fields to reduce payload size
308
+ for (const key of Object.keys(entry)) {
309
+ if (entry[key] == null) {
310
+ delete entry[key];
311
+ }
312
+ }
313
+
314
+ return entry;
303
315
  });
304
316
 
305
- return {
317
+ const response = {
306
318
  results: transformedResults,
307
319
  totalEstimatedMatches: Number(resultObject.totalEstimatedMatches || 0),
308
320
  moreAvailable: Boolean(resultObject.moreAvailable),
@@ -312,6 +324,24 @@ export function registerTools(registry, context) {
312
324
  : from + transformedResults.length,
313
325
  warnings: Array.isArray(resultObject.warnings) ? resultObject.warnings : []
314
326
  };
327
+
328
+ const responseJson = JSON.stringify(response);
329
+ const responseBytes = Buffer.byteLength(responseJson, "utf-8");
330
+
331
+ if (responseBytes > SEARCH_FILE_THRESHOLD) {
332
+ const filePath = context.tempFiles.write(responseJson);
333
+ return {
334
+ result_count: transformedResults.length,
335
+ file_path: filePath,
336
+ file_size_bytes: responseBytes,
337
+ totalEstimatedMatches: response.totalEstimatedMatches,
338
+ moreAvailable: response.moreAvailable,
339
+ nextFrom: response.nextFrom,
340
+ warnings: response.warnings
341
+ };
342
+ }
343
+
344
+ return response;
315
345
  });
316
346
 
317
347
  registry.addTool(OPEN_TOOL, async (args) => {
@@ -336,7 +366,68 @@ export function registerTools(registry, context) {
336
366
  { timeoutMs: args.fullContent ? 90000 : 60000 }
337
367
  );
338
368
 
339
- return asObject(wsResult);
369
+ const result = asObject(wsResult);
370
+ if (!Object.hasOwn(result, "content")) {
371
+ throw new Error("Extension response missing content for this item.");
372
+ }
373
+ const content = typeof result.content === "string"
374
+ ? result.content
375
+ : (result.content != null ? JSON.stringify(result.content, null, 2) : "");
376
+ const contentBytes = Buffer.byteLength(content, "utf-8");
377
+
378
+ const useFile = contentBytes > OPEN_FILE_THRESHOLD;
379
+
380
+ const summary = {
381
+ type: readContext.type || result.type || "",
382
+ title: readContext.title || result.title || "",
383
+ url: readContext.url || result.url || "",
384
+ snippet: readContext.snippet || "",
385
+ completeness: result.completeness || "unknown"
386
+ };
387
+
388
+ if (useFile) {
389
+ summary.file_path = context.tempFiles.write(content);
390
+ summary.file_size_bytes = contentBytes;
391
+ } else {
392
+ summary.content = content;
393
+ }
394
+
395
+ // Carry over key metadata from readContext and result.metadata
396
+ // Email _readContext has no metadata object; fields may be at readContext top level.
397
+ // Content reader returns result.metadata with additional fields.
398
+ const meta = { ...asObject(readContext.metadata), ...asObject(result.metadata) };
399
+ if (readContext.type === "email") {
400
+ const from = meta.from || readContext.from;
401
+ // Graph returns toRecipients (array of strings or {emailAddress} objects) and receivedDateTime
402
+ const rawTo = meta.toRecipients || meta.to || readContext.to;
403
+ const to = Array.isArray(rawTo)
404
+ ? rawTo.map((r) => (typeof r === "string" ? r : (r?.emailAddress?.address || r?.emailAddress?.name || String(r)))).join(", ")
405
+ : rawTo;
406
+ const subject = meta.subject || readContext.subject;
407
+ const date = meta.receivedDateTime || meta.date || readContext.date;
408
+ if (from) summary.from = from;
409
+ if (to) summary.to = to;
410
+ if (subject) summary.subject = subject;
411
+ if (date) summary.date = date;
412
+ } else if (readContext.type === "file") {
413
+ if (meta.author) summary.author = meta.author;
414
+ if (meta.fileType) summary.fileType = meta.fileType;
415
+ } else if (readContext.type === "chat") {
416
+ if (meta.from) summary.from = meta.from;
417
+ if (meta.teamName) summary.teamName = meta.teamName;
418
+ if (meta.channelName) summary.channelName = meta.channelName;
419
+ } else if (readContext.type === "event") {
420
+ if (meta.location) summary.location = meta.location;
421
+ if (meta.startTime) summary.startTime = meta.startTime;
422
+ if (meta.endTime) summary.endTime = meta.endTime;
423
+ if (meta.organizer) summary.organizer = meta.organizer;
424
+ }
425
+
426
+ if (result.warning) {
427
+ summary.warning = result.warning;
428
+ }
429
+
430
+ return summary;
340
431
  });
341
432
 
342
433
  registry.addTool(WHOAMI_TOOL, async (args) => {