@teamnetwork-nz/m365-mcp-server 1.7.0 → 1.7.2

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 CHANGED
@@ -192,7 +192,7 @@ Operations always target exactly one mailbox per request, either the default or
192
192
  | `reply_message` | Reply or reply-all to a message (non-readonly mailboxes only) |
193
193
  | `move_message` | Move a message to another folder (non-readonly mailboxes only) |
194
194
  | `list_message_attachments` | List all attachments on a message (file, item, and reference types) |
195
- | `download_attachment` | Download a file attachment as base64. Images returned as MCP image content; reference attachments return their preview URL |
195
+ | `download_attachment` | Download an attachment. Pass `savePath` to write decoded bytes directly beneath a configured `attachmentDownloads.allowedRoots` directory and receive its path, byte count, and SHA-256. Otherwise returns base64 inline; images use MCP image content |
196
196
 
197
197
  ### Calendar
198
198
 
@@ -24,6 +24,9 @@
24
24
  ]
25
25
  }
26
26
  ],
27
+ "attachmentDownloads": {
28
+ "allowedRoots": ["C:\\Users\\you\\Downloads\\M365"]
29
+ },
27
30
  "sharepoint": [
28
31
  {
29
32
  "id": "company-docs",
@@ -52,10 +52,14 @@ export const TeamsConfigSchema = z.object({
52
52
  channelMessagesAllowed: z.boolean().default(false),
53
53
  chatMessagesAllowed: z.boolean().default(false),
54
54
  });
55
+ export const AttachmentDownloadsConfigSchema = z.object({
56
+ allowedRoots: z.array(z.string().min(1)).min(1),
57
+ });
55
58
  // ── Root config ─────────────────────────────────────────────────────────────
56
59
  export const AppConfigSchema = z.object({
57
60
  connection: ConnectionConfigSchema,
58
61
  accounts: z.array(AccountConfigSchema).min(1, 'Config must have at least one account'),
62
+ attachmentDownloads: AttachmentDownloadsConfigSchema.optional(),
59
63
  sharepoint: z.array(SharepointLibraryConfigSchema).optional(),
60
64
  teams: TeamsConfigSchema.optional(),
61
65
  });
package/dist/env.js ADDED
@@ -0,0 +1,12 @@
1
+ export function parsePositiveInt(name, raw, fallback, maximum) {
2
+ if (raw === undefined || raw.trim() === '')
3
+ return fallback;
4
+ if (!/^\d+$/.test(raw.trim())) {
5
+ throw new Error(`${name} must be an integer from 1 to ${maximum}`);
6
+ }
7
+ const value = Number(raw);
8
+ if (!Number.isSafeInteger(value) || value < 1 || value > maximum) {
9
+ throw new Error(`${name} must be an integer from 1 to ${maximum}`);
10
+ }
11
+ return value;
12
+ }
@@ -64,9 +64,10 @@ export function createHttpServer(factory, o) {
64
64
  return error(res, 405, -32000, "Method not allowed");
65
65
  }
66
66
  const server = factory();
67
- const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
67
+ const transport = new StreamableHTTPServerTransport();
68
68
  try {
69
69
  const body = await readBody(req, o.maxBodyBytes ?? 1048576);
70
+ // SDK 1.29's class getter types conflict with Transport only under exactOptionalPropertyTypes.
70
71
  await server.connect(transport);
71
72
  await transport.handleRequest(req, res, body);
72
73
  res.once("close", () => { void transport.close(); void server.close(); });
package/dist/index.js CHANGED
@@ -7,6 +7,9 @@ import { AuthManager } from './auth/AuthManager.js';
7
7
  import { registerAllTools } from './tools/registry.js';
8
8
  import { logger } from './utils/logger.js';
9
9
  import { createHttpServer } from './http-server.js';
10
+ import { packageName, packageVersion } from './package-info.js';
11
+ import { enforceStrictToolInputs } from './strict-tools.js';
12
+ import { parsePositiveInt } from './env.js';
10
13
  async function main() {
11
14
  // 1. Load and validate config — aborts if invalid
12
15
  const config = loadConfig();
@@ -17,8 +20,8 @@ async function main() {
17
20
  // 3. Create MCP server and register all tools
18
21
  const createConfiguredServer = () => {
19
22
  const server = new McpServer({
20
- name: '@teamnetwork/m365-mcp-server',
21
- version: '1.7.0',
23
+ name: packageName,
24
+ version: packageVersion,
22
25
  }, {
23
26
  instructions: `
24
27
  Microsoft 365 MCP server — email, calendar, and To Do via the Microsoft Graph API.
@@ -49,14 +52,15 @@ Microsoft 365 MCP server — email, calendar, and To Do via the Microsoft Graph
49
52
  - delete_todo_task is permanent and irreversible. Confirm with the user before calling it.
50
53
  `.trim(),
51
54
  });
55
+ enforceStrictToolInputs(server);
52
56
  registerAllTools(server, config, auth);
53
57
  return server;
54
58
  };
55
59
  // 4. Connect via stdio transport (Claude Desktop / Claude Code)
56
60
  if ((process.env['M365_TRANSPORT'] ?? 'stdio') === 'http') {
57
61
  const host = process.env['M365_HTTP_HOST'] ?? '127.0.0.1';
58
- const port = Number.parseInt(process.env['M365_HTTP_PORT'] ?? '3000', 10);
59
- createHttpServer(createConfiguredServer, { host, port, serverName: '@teamnetwork/m365-mcp-server', bearerToken: process.env['M365_HTTP_BEARER_TOKEN'], allowedHosts: process.env['M365_HTTP_ALLOWED_HOSTS']?.split(',').map(v => v.trim()).filter(Boolean), allowedOrigins: process.env['M365_HTTP_ALLOWED_ORIGINS']?.split(',').map(v => v.trim()).filter(Boolean), maxBodyBytes: Number.parseInt(process.env['M365_HTTP_MAX_BODY_BYTES'] ?? '1048576', 10) }).listen(port, host, () => logger.info(`M365 MCP server listening on ${host}:${port}/mcp`));
62
+ const port = parsePositiveInt('M365_HTTP_PORT', process.env['M365_HTTP_PORT'], 3000, 65535);
63
+ createHttpServer(createConfiguredServer, { host, port, serverName: packageName, bearerToken: process.env['M365_HTTP_BEARER_TOKEN'], allowedHosts: process.env['M365_HTTP_ALLOWED_HOSTS']?.split(',').map(v => v.trim()).filter(Boolean), allowedOrigins: process.env['M365_HTTP_ALLOWED_ORIGINS']?.split(',').map(v => v.trim()).filter(Boolean), maxBodyBytes: parsePositiveInt('M365_HTTP_MAX_BODY_BYTES', process.env['M365_HTTP_MAX_BODY_BYTES'], 1_048_576, 16_777_216) }).listen(port, host, () => logger.info(`M365 MCP server listening on ${host}:${port}/mcp`));
60
64
  }
61
65
  else {
62
66
  await createConfiguredServer().connect(new StdioServerTransport());
@@ -0,0 +1,6 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ const packageJson = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf8'));
5
+ export const packageName = packageJson.name ?? 'm365-mcp-server';
6
+ export const packageVersion = packageJson.version ?? '0.0.0';
@@ -0,0 +1,29 @@
1
+ import { z } from "zod";
2
+ function isSchema(value) {
3
+ return typeof value === "object" && value !== null && "_def" in value;
4
+ }
5
+ function isRawShape(value) {
6
+ if (typeof value !== "object" || value === null || isSchema(value))
7
+ return false;
8
+ const values = Object.values(value);
9
+ return values.length === 0 || values.some(isSchema);
10
+ }
11
+ function strictSchema(schema) {
12
+ if (schema === undefined)
13
+ return z.object({}).strict();
14
+ if (isRawShape(schema))
15
+ return z.object(schema).strict();
16
+ if (isSchema(schema) && typeof schema.strict === "function")
17
+ return schema.strict();
18
+ return schema;
19
+ }
20
+ /** Make every tool object reject undeclared arguments, including no-argument tools. */
21
+ export function enforceStrictToolInputs(server) {
22
+ const mutable = server;
23
+ const createRegisteredTool = mutable._createRegisteredTool.bind(server);
24
+ mutable._createRegisteredTool = (...args) => {
25
+ // SDK 1.29 funnels both tool() and registerTool() through this method.
26
+ args[3] = strictSchema(args[3]);
27
+ return createRegisteredTool(...args);
28
+ };
29
+ }
@@ -5,8 +5,9 @@ import { assertMailboxConfigured } from '../../middleware/readonlyGuard.js';
5
5
  import { errorResponse } from '../../utils/errors.js';
6
6
  import { logger } from '../../utils/logger.js';
7
7
  import { resolveMailbox } from '../../utils/resolveMailbox.js';
8
+ import { writeAttachmentFile } from '../../utils/attachmentFile.js';
8
9
  export function registerDownloadAttachment(server, config, auth) {
9
- server.tool('download_attachment', 'Download one attachment using its messageId and attachmentId from list_message_attachments. File attachments return base64 content (images use MCP image content); reference attachments return their preview URL; embedded Outlook items return a description. Omit accountId/mailbox to use the default configured mailbox.', DownloadAttachmentSchema.shape, async (params) => {
10
+ server.tool('download_attachment', 'Download one attachment using its messageId and attachmentId from list_message_attachments. Pass savePath to write file bytes directly beneath a server-configured attachmentDownloads.allowedRoots directory and receive a small integrity summary. Without savePath, file attachments return base64 content (images use MCP image content). Reference attachments return their preview URL; embedded Outlook items return a description. Omit accountId/mailbox to use the default configured mailbox.', DownloadAttachmentSchema.shape, async (params) => {
10
11
  try {
11
12
  const resolved = resolveMailbox(config, params.accountId, params.mailbox);
12
13
  logger.info('download_attachment', { accountId: resolved.accountId, mailbox: resolved.mailbox });
@@ -16,6 +17,18 @@ export function registerDownloadAttachment(server, config, auth) {
16
17
  const result = await downloadAttachment(client, resolved.mailbox, params.messageId, params.attachmentId);
17
18
  switch (result.kind) {
18
19
  case 'file':
20
+ if (params.savePath) {
21
+ const written = await writeAttachmentFile(result.contentBytes, params.savePath, config.attachmentDownloads?.allowedRoots);
22
+ const response = {
23
+ fileName: result.name,
24
+ mimeType: result.mimeType,
25
+ ...written,
26
+ };
27
+ return {
28
+ content: [{ type: 'text', text: JSON.stringify(response, null, 2) }],
29
+ structuredContent: response,
30
+ };
31
+ }
19
32
  if (result.mimeType.startsWith('image/')) {
20
33
  return {
21
34
  content: [{ type: 'image', data: result.contentBytes, mimeType: result.mimeType }],
@@ -46,6 +46,7 @@ export const ListMessageAttachmentsSchema = AccountMailbox.extend({
46
46
  export const DownloadAttachmentSchema = AccountMailbox.extend({
47
47
  messageId: z.string().describe('The message ID'),
48
48
  attachmentId: z.string().describe('The attachment ID to download'),
49
+ savePath: z.string().optional().describe('Absolute local path to write the decoded attachment. The path must be beneath an attachmentDownloads.allowedRoots directory configured on the server. Existing files are never overwritten. Omit to return content inline.'),
49
50
  });
50
51
  export const SendMessageSchema = AccountMailbox.extend({
51
52
  to: z.array(z.string().email()).min(1).describe('List of recipient email addresses'),
@@ -0,0 +1,104 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { constants } from 'node:fs';
3
+ import { copyFile, link, lstat, unlink, writeFile } from 'node:fs/promises';
4
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
5
+ import { ToolError } from './errors.js';
6
+ function isWithin(root, candidate) {
7
+ const rel = relative(root, candidate);
8
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
9
+ }
10
+ function decodeBase64(value) {
11
+ const compact = value.replace(/\s/g, '');
12
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(compact) || compact.length % 4 === 1) {
13
+ throw new ToolError('Graph returned invalid base64 attachment content.', 'INVALID_ATTACHMENT_CONTENT');
14
+ }
15
+ const unpadded = compact.replace(/=+$/, '');
16
+ const padded = unpadded.padEnd(Math.ceil(unpadded.length / 4) * 4, '=');
17
+ const bytes = Buffer.from(padded, 'base64');
18
+ if (bytes.toString('base64').replace(/=+$/, '') !== unpadded) {
19
+ throw new ToolError('Graph returned invalid base64 attachment content.', 'INVALID_ATTACHMENT_CONTENT');
20
+ }
21
+ return bytes;
22
+ }
23
+ async function assertExistingPathHasNoLinks(root, parent) {
24
+ const rel = relative(root, parent);
25
+ const paths = [root];
26
+ let current = root;
27
+ for (const segment of rel.split(sep).filter(Boolean)) {
28
+ current = resolve(current, segment);
29
+ paths.push(current);
30
+ }
31
+ for (const path of paths) {
32
+ let stat;
33
+ try {
34
+ stat = await lstat(path);
35
+ }
36
+ catch (err) {
37
+ if (err.code === 'ENOENT') {
38
+ throw new ToolError(`The savePath directory does not exist: "${path}".`, 'INVALID_SAVE_PATH');
39
+ }
40
+ throw new ToolError(`Could not inspect savePath directory "${path}": ${err.message}`, 'INVALID_SAVE_PATH');
41
+ }
42
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
43
+ throw new ToolError(`Attachment download paths must use existing directories without symbolic links: "${path}".`, 'INVALID_SAVE_PATH');
44
+ }
45
+ }
46
+ }
47
+ export async function writeAttachmentFile(contentBytes, savePath, allowedRoots) {
48
+ if (!allowedRoots?.length) {
49
+ throw new ToolError('Saving attachments is disabled. Configure attachmentDownloads.allowedRoots on the server.', 'ATTACHMENT_DOWNLOAD_DISABLED');
50
+ }
51
+ if (!isAbsolute(savePath)) {
52
+ throw new ToolError('savePath must be an absolute path.', 'INVALID_SAVE_PATH');
53
+ }
54
+ const destination = resolve(savePath);
55
+ const destinationParent = dirname(destination);
56
+ let allowed = false;
57
+ for (const configuredRoot of allowedRoots) {
58
+ if (!isAbsolute(configuredRoot)) {
59
+ throw new ToolError(`Configured attachment download root must be absolute: "${configuredRoot}".`, 'INVALID_DOWNLOAD_CONFIG');
60
+ }
61
+ const resolvedRoot = resolve(configuredRoot);
62
+ if (isWithin(resolvedRoot, destination)) {
63
+ await assertExistingPathHasNoLinks(resolvedRoot, destinationParent);
64
+ allowed = true;
65
+ break;
66
+ }
67
+ }
68
+ if (!allowed) {
69
+ throw new ToolError('savePath is outside the configured attachmentDownloads.allowedRoots.', 'SAVE_PATH_NOT_ALLOWED');
70
+ }
71
+ const bytes = decodeBase64(contentBytes);
72
+ const tempPath = `${destination}.${randomUUID()}.tmp`;
73
+ try {
74
+ await writeFile(tempPath, bytes, { flag: 'wx', mode: 0o600 });
75
+ // A hard link publishes the completed file atomically and fails if the
76
+ // destination already exists. This avoids platform-specific rename overwrite behavior.
77
+ try {
78
+ await link(tempPath, destination);
79
+ }
80
+ catch (err) {
81
+ // Some sandboxed Windows filesystems prohibit hard links. COPYFILE_EXCL
82
+ // preserves the critical no-overwrite guarantee in that environment.
83
+ if (err.code !== 'EPERM')
84
+ throw err;
85
+ await copyFile(tempPath, destination, constants.COPYFILE_EXCL);
86
+ }
87
+ }
88
+ catch (err) {
89
+ if (err.code === 'EEXIST') {
90
+ throw new ToolError(`Refusing to overwrite existing file: "${destination}".`, 'FILE_EXISTS');
91
+ }
92
+ if (err instanceof ToolError)
93
+ throw err;
94
+ throw new ToolError(`Could not write attachment to "${destination}": ${err.message}`, 'ATTACHMENT_WRITE_FAILED');
95
+ }
96
+ finally {
97
+ await unlink(tempPath).catch(() => undefined);
98
+ }
99
+ return {
100
+ writtenTo: destination,
101
+ bytes: bytes.byteLength,
102
+ sha256: createHash('sha256').update(bytes).digest('hex'),
103
+ };
104
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamnetwork-nz/m365-mcp-server",
3
- "version": "1.7.0",
3
+ "version": "1.7.2",
4
4
  "description": "MCP server for Microsoft 365 — Email, Calendar, To Do, SharePoint document libraries, and Teams — using client credentials (app-only auth). Supports multiple accounts, shared mailboxes, per-mailbox read-only access, and grant-based SharePoint access control.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -37,8 +37,8 @@
37
37
  "dependencies": {
38
38
  "@azure/msal-node": "^2.16.0",
39
39
  "@microsoft/microsoft-graph-client": "^3.0.7",
40
- "@modelcontextprotocol/sdk": "^1.10.0",
41
- "zod": "^3.23.0"
40
+ "@modelcontextprotocol/sdk": "^1.29.0",
41
+ "zod": "^3.25.0"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@types/node": "^20.0.0",