@teamnetwork-nz/m365-mcp-server 1.3.0 → 1.5.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 +5 -1
- package/dist/http-server.js +83 -0
- package/dist/index.js +20 -10
- package/dist/tools/schemas.js +23 -3
- package/dist/tools/sharepoint/uploadFile.js +20 -5
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# @teamnetwork-nz/m365-mcp-server
|
|
2
2
|
|
|
3
|
+
## Streamable HTTP
|
|
4
|
+
|
|
5
|
+
Set `M365_TRANSPORT=http` to serve stateless MCP at `/mcp`. It binds to `127.0.0.1` by default; remote binding requires `M365_HTTP_BEARER_TOKEN` and `M365_HTTP_ALLOWED_HOSTS`. Optional controls include `M365_HTTP_PORT`, `M365_HTTP_ALLOWED_ORIGINS`, and `M365_HTTP_MAX_BODY_BYTES`; `/health` is available for health checks.
|
|
6
|
+
|
|
3
7
|
A [Model Context Protocol (MCP)](https://modelcontextprotocol.io) server for Microsoft 365 — Email, Calendar, To Do, and SharePoint document libraries — using **app-only (client credentials) authentication** — no user login flows required.
|
|
4
8
|
|
|
5
9
|
Supports multiple accounts, shared mailboxes, per-mailbox read-only access control, folder navigation, date/content filtering, and grant-based SharePoint access control.
|
|
@@ -225,7 +229,7 @@ Operations always target exactly one mailbox per request, either the default or
|
|
|
225
229
|
| `get_drive_item` | Get metadata for a file or folder — always permitted, no grant required |
|
|
226
230
|
| `check_sharepoint_access` | Check whether an operation is permitted by the grant config (no network call, never errors) — use before content operations |
|
|
227
231
|
| `download_file` | Download a file as base64. Images returned as MCP image content; others as a JSON payload with `fileName`, `mimeType`, `encoding`, and `data`. Requires `read` grant |
|
|
228
|
-
| `upload_file` | Upload a file (
|
|
232
|
+
| `upload_file` | Upload a file (max 4 MB) via `sourcePath` (preferred — reads from disk) or inline `content` (`contentEncoding: "utf8"` or `"base64"`, optionally checked against `expectedBytes`/`sha256`). Creates or overwrites. Requires `create` or `update` grant |
|
|
229
233
|
| `create_folder` | Create a new folder. Requires `create` grant on the parent path |
|
|
230
234
|
| `delete_drive_item` | Permanently delete a file or folder. Requires `delete` grant |
|
|
231
235
|
| `move_drive_item` | Move a file or folder, optionally renaming. Requires `update` at source and `create` at destination |
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { timingSafeEqual } from "node:crypto";
|
|
2
|
+
import http from "node:http";
|
|
3
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
4
|
+
const loopback = new Set(["127.0.0.1", "::1", "localhost"]);
|
|
5
|
+
const send = (res, status, body) => {
|
|
6
|
+
res.writeHead(status, { "Content-Type": "application/json" }).end(JSON.stringify(body));
|
|
7
|
+
};
|
|
8
|
+
const error = (res, status, code, message) => send(res, status, { jsonrpc: "2.0", error: { code, message }, id: null });
|
|
9
|
+
const matches = (value, expected) => {
|
|
10
|
+
if (!value?.startsWith("Bearer "))
|
|
11
|
+
return false;
|
|
12
|
+
const supplied = Buffer.from(value.slice(7));
|
|
13
|
+
const wanted = Buffer.from(expected);
|
|
14
|
+
return supplied.length === wanted.length && timingSafeEqual(supplied, wanted);
|
|
15
|
+
};
|
|
16
|
+
const readBody = (req, limit) => new Promise((resolve, reject) => {
|
|
17
|
+
const chunks = [];
|
|
18
|
+
let size = 0;
|
|
19
|
+
let oversized = false;
|
|
20
|
+
req.on("data", (chunk) => { size += chunk.length; oversized ||= size > limit; if (!oversized)
|
|
21
|
+
chunks.push(chunk); });
|
|
22
|
+
req.on("end", () => {
|
|
23
|
+
if (oversized)
|
|
24
|
+
return reject(Object.assign(new Error("Request body too large"), { statusCode: 413 }));
|
|
25
|
+
try {
|
|
26
|
+
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
reject(Object.assign(new Error("Invalid JSON body"), { statusCode: 400 }));
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
req.on("error", reject);
|
|
33
|
+
});
|
|
34
|
+
export function validateHttpOptions(o) {
|
|
35
|
+
if (!Number.isInteger(o.port) || o.port < 1 || o.port > 65535)
|
|
36
|
+
throw new Error(`Invalid HTTP port: ${o.port}`);
|
|
37
|
+
if (o.maxBodyBytes !== undefined && (!Number.isInteger(o.maxBodyBytes) || o.maxBodyBytes < 1))
|
|
38
|
+
throw new Error(`Invalid HTTP body limit: ${o.maxBodyBytes}`);
|
|
39
|
+
if (!loopback.has(o.host) && !o.bearerToken)
|
|
40
|
+
throw new Error("A bearer token is required when binding beyond loopback");
|
|
41
|
+
if (!loopback.has(o.host) && !o.allowedHosts?.length)
|
|
42
|
+
throw new Error("HTTP_ALLOWED_HOSTS is required when binding beyond loopback");
|
|
43
|
+
}
|
|
44
|
+
export function createHttpServer(factory, o) {
|
|
45
|
+
validateHttpOptions(o);
|
|
46
|
+
const hosts = new Set(o.allowedHosts?.map(v => v.toLowerCase()));
|
|
47
|
+
const origins = new Set(o.allowedOrigins?.map(v => v.toLowerCase()));
|
|
48
|
+
return http.createServer(async (req, res) => {
|
|
49
|
+
const path = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
50
|
+
if (path === "/health")
|
|
51
|
+
return send(res, 200, { status: "ok", server: o.serverName });
|
|
52
|
+
if (path !== "/mcp")
|
|
53
|
+
return void res.writeHead(404).end();
|
|
54
|
+
if (hosts.size && !hosts.has((req.headers.host ?? "").toLowerCase()))
|
|
55
|
+
return error(res, 403, -32000, "Host not allowed");
|
|
56
|
+
if (req.headers.origin && !origins.has(req.headers.origin.toLowerCase()))
|
|
57
|
+
return error(res, 403, -32000, "Origin not allowed");
|
|
58
|
+
if (o.bearerToken && !matches(req.headers.authorization, o.bearerToken)) {
|
|
59
|
+
res.setHeader("WWW-Authenticate", "Bearer");
|
|
60
|
+
return error(res, 401, -32001, "Unauthorized");
|
|
61
|
+
}
|
|
62
|
+
if (req.method !== "POST") {
|
|
63
|
+
res.setHeader("Allow", "POST");
|
|
64
|
+
return error(res, 405, -32000, "Method not allowed");
|
|
65
|
+
}
|
|
66
|
+
const server = factory();
|
|
67
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
|
|
68
|
+
try {
|
|
69
|
+
const body = await readBody(req, o.maxBodyBytes ?? 1048576);
|
|
70
|
+
await server.connect(transport);
|
|
71
|
+
await transport.handleRequest(req, res, body);
|
|
72
|
+
res.once("close", () => { void transport.close(); void server.close(); });
|
|
73
|
+
}
|
|
74
|
+
catch (cause) {
|
|
75
|
+
void transport.close();
|
|
76
|
+
void server.close();
|
|
77
|
+
if (!res.headersSent) {
|
|
78
|
+
const status = cause.statusCode ?? 500;
|
|
79
|
+
error(res, status, status === 400 ? -32700 : -32603, status < 500 ? cause.message : "Internal server error");
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -6,6 +6,7 @@ import { TokenCache } from './auth/TokenCache.js';
|
|
|
6
6
|
import { AuthManager } from './auth/AuthManager.js';
|
|
7
7
|
import { registerAllTools } from './tools/registry.js';
|
|
8
8
|
import { logger } from './utils/logger.js';
|
|
9
|
+
import { createHttpServer } from './http-server.js';
|
|
9
10
|
async function main() {
|
|
10
11
|
// 1. Load and validate config — aborts if invalid
|
|
11
12
|
const config = loadConfig();
|
|
@@ -14,11 +15,12 @@ async function main() {
|
|
|
14
15
|
const tokenCache = new TokenCache(config);
|
|
15
16
|
const auth = new AuthManager(tokenCache);
|
|
16
17
|
// 3. Create MCP server and register all tools
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
18
|
+
const createConfiguredServer = () => {
|
|
19
|
+
const server = new McpServer({
|
|
20
|
+
name: '@teamnetwork/m365-mcp-server',
|
|
21
|
+
version: '1.5.0',
|
|
22
|
+
}, {
|
|
23
|
+
instructions: `
|
|
22
24
|
Microsoft 365 MCP server — email, calendar, and To Do via the Microsoft Graph API.
|
|
23
25
|
|
|
24
26
|
## Accounts and mailboxes
|
|
@@ -46,12 +48,20 @@ Microsoft 365 MCP server — email, calendar, and To Do via the Microsoft Graph
|
|
|
46
48
|
- Linked resources (list_linked_resources, create_linked_resource, etc.) are external URL attachments on a task — they are not subtasks. Subtasks appear as checklistItems inside the task body.
|
|
47
49
|
- delete_todo_task is permanent and irreversible. Confirm with the user before calling it.
|
|
48
50
|
`.trim(),
|
|
49
|
-
|
|
50
|
-
|
|
51
|
+
});
|
|
52
|
+
registerAllTools(server, config, auth);
|
|
53
|
+
return server;
|
|
54
|
+
};
|
|
51
55
|
// 4. Connect via stdio transport (Claude Desktop / Claude Code)
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
56
|
+
if ((process.env['M365_TRANSPORT'] ?? 'stdio') === 'http') {
|
|
57
|
+
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`));
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
await createConfiguredServer().connect(new StdioServerTransport());
|
|
63
|
+
logger.info('M365 MCP server running on stdio');
|
|
64
|
+
}
|
|
55
65
|
}
|
|
56
66
|
main().catch((err) => {
|
|
57
67
|
process.stderr.write(`Fatal: ${err.message ?? String(err)}\n`);
|
package/dist/tools/schemas.js
CHANGED
|
@@ -199,9 +199,29 @@ export const UploadFileSchema = SharepointBase.extend({
|
|
|
199
199
|
content: z
|
|
200
200
|
.string()
|
|
201
201
|
.optional()
|
|
202
|
-
.describe('
|
|
203
|
-
'for anything larger, or
|
|
204
|
-
'instead.
|
|
202
|
+
.describe('Inline file content, interpreted per contentEncoding (default base64). Only use this for ' +
|
|
203
|
+
'small files supplied inline — for anything larger, or a file that already exists on disk, ' +
|
|
204
|
+
'use sourcePath instead. For text files, prefer contentEncoding "utf8" so no base64 is ' +
|
|
205
|
+
'needed. Exactly one of sourcePath or content must be provided. Maximum 4 MB.'),
|
|
206
|
+
contentEncoding: z
|
|
207
|
+
.enum(['base64', 'utf8'])
|
|
208
|
+
.default('base64')
|
|
209
|
+
.describe('How to interpret content. "utf8" = plain text sent as-is (recommended for .md, .txt, .csv, ' +
|
|
210
|
+
'.json etc. — avoids error-prone base64). "base64" = binary files. Ignored for sourcePath.'),
|
|
211
|
+
expectedBytes: z
|
|
212
|
+
.number()
|
|
213
|
+
.int()
|
|
214
|
+
.nonnegative()
|
|
215
|
+
.optional()
|
|
216
|
+
.describe('Optional integrity check: the exact size in bytes the file should have after decoding. ' +
|
|
217
|
+
'If the received content decodes to a different size, the upload is rejected before ' +
|
|
218
|
+
'anything is written — this catches truncated or corrupted inline content.'),
|
|
219
|
+
sha256: z
|
|
220
|
+
.string()
|
|
221
|
+
.regex(/^[0-9a-fA-F]{64}$/, 'sha256 must be a 64-character hex string')
|
|
222
|
+
.optional()
|
|
223
|
+
.describe('Optional integrity check: hex SHA-256 of the file bytes. If the received content does not ' +
|
|
224
|
+
'match, the upload is rejected before anything is written.'),
|
|
205
225
|
contentType: z
|
|
206
226
|
.string()
|
|
207
227
|
.optional()
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
1
2
|
import { readFile } from 'node:fs/promises';
|
|
2
3
|
import { UploadFileSchema } from '../schemas.js';
|
|
3
4
|
import { createGraphClient } from '../../graph/clientFactory.js';
|
|
@@ -13,10 +14,11 @@ export function registerUploadFile(server, config, auth) {
|
|
|
13
14
|
server.tool('upload_file', 'Upload a file to a SharePoint document library. Creates the file if it does not exist; ' +
|
|
14
15
|
'overwrites it if it does (SharePoint manages version history). ' +
|
|
15
16
|
'Provide exactly one of sourcePath or content: sourcePath (preferred) reads an existing ' +
|
|
16
|
-
'local file directly from disk; content is
|
|
17
|
-
'
|
|
18
|
-
'
|
|
19
|
-
'
|
|
17
|
+
'local file directly from disk; content is for small inline payloads only — use ' +
|
|
18
|
+
'contentEncoding "utf8" for text files (no base64), "base64" for binary. Long base64 ' +
|
|
19
|
+
'emitted inline can be truncated or corrupted by the caller with no error, so pass ' +
|
|
20
|
+
'expectedBytes and/or sha256 with inline content: a mismatch rejects the upload before ' +
|
|
21
|
+
'anything is written. Prefer sourcePath for anything above a few KB. ' +
|
|
20
22
|
'Maximum 4 MB. Requires a grant with "create" OR "update" in allowedOperations for the path ' +
|
|
21
23
|
'and filename. Call check_sharepoint_access first to verify permissions.', UploadFileSchema.shape, async (params) => {
|
|
22
24
|
try {
|
|
@@ -43,7 +45,20 @@ export function registerUploadFile(server, config, auth) {
|
|
|
43
45
|
}
|
|
44
46
|
}
|
|
45
47
|
else {
|
|
46
|
-
buf = Buffer.from(params.content, 'base64');
|
|
48
|
+
buf = Buffer.from(params.content, params.contentEncoding === 'utf8' ? 'utf8' : 'base64');
|
|
49
|
+
}
|
|
50
|
+
// Integrity checks — reject before any Graph call if the decoded bytes are wrong.
|
|
51
|
+
if (params.expectedBytes !== undefined && buf.byteLength !== params.expectedBytes) {
|
|
52
|
+
throw new ToolError(`Integrity check failed: expected ${params.expectedBytes} bytes but received ` +
|
|
53
|
+
`${buf.byteLength}. The content was likely truncated or corrupted in transit — ` +
|
|
54
|
+
'nothing was uploaded.', 'INTEGRITY_CHECK_FAILED');
|
|
55
|
+
}
|
|
56
|
+
if (params.sha256 !== undefined) {
|
|
57
|
+
const actual = createHash('sha256').update(buf).digest('hex');
|
|
58
|
+
if (actual !== params.sha256.toLowerCase()) {
|
|
59
|
+
throw new ToolError(`Integrity check failed: SHA-256 mismatch (received ${actual}). The content was ` +
|
|
60
|
+
'likely truncated or corrupted in transit — nothing was uploaded.', 'INTEGRITY_CHECK_FAILED');
|
|
61
|
+
}
|
|
47
62
|
}
|
|
48
63
|
if (buf.byteLength > MAX_BYTES) {
|
|
49
64
|
throw new ToolError(`File is ${(buf.byteLength / 1024 / 1024).toFixed(1)} MB which exceeds the 4 MB ` +
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@teamnetwork-nz/m365-mcp-server",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
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",
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
],
|
|
14
14
|
"scripts": {
|
|
15
15
|
"build": "tsc",
|
|
16
|
+
"test": "npm run build && node --test tests/*.test.mjs",
|
|
16
17
|
"prepare": "npm run build",
|
|
17
18
|
"start": "node dist/index.js",
|
|
18
19
|
"dev": "tsx watch src/index.ts"
|