@teamnetwork-nz/m365-mcp-server 1.4.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 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.
@@ -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 server = new McpServer({
18
- name: '@teamnetwork/m365-mcp-server',
19
- version: '1.3.0',
20
- }, {
21
- instructions: `
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
- registerAllTools(server, config, auth);
51
+ });
52
+ registerAllTools(server, config, auth);
53
+ return server;
54
+ };
51
55
  // 4. Connect via stdio transport (Claude Desktop / Claude Code)
52
- const transport = new StdioServerTransport();
53
- await server.connect(transport);
54
- logger.info('M365 MCP server running on stdio');
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamnetwork-nz/m365-mcp-server",
3
- "version": "1.4.0",
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"