@bold-tech-npm/graph-mcp 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bold Tech
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,61 @@
1
+ # @bold-tech-npm/graph-mcp
2
+
3
+ A small [MCP](https://modelcontextprotocol.io) server that exposes **Microsoft Graph** (Outlook)
4
+ to an AI client, with two things most Graph connectors get wrong:
5
+
6
+ - **Device-code auth** — no client secret, no redirect URI. The signed-in user consents in a
7
+ browser; the server acts *as that user* (delegated, security-trimmed), so it only ever sees what
8
+ they're permitted to see.
9
+ - **Smart inbox reads** — an overnight burst of long, multi-message threads is collapsed to **one
10
+ item per thread** (by `conversationId` *or* normalized subject), with unread and date-window
11
+ filters, so the model gets a clean list instead of a confusing pile.
12
+
13
+ Configuration is entirely via environment variables, so one published package serves many
14
+ tenants/clients.
15
+
16
+ ## Configure
17
+
18
+ | Env var | Required | Default | Notes |
19
+ |---|---|---|---|
20
+ | `GRAPH_CLIENT_ID` | ✅ | — | Entra app registration (public client, device-code enabled) |
21
+ | `GRAPH_TENANT_ID` | ✅ | — | The tenant that owns the mailbox |
22
+ | `GRAPH_SCOPES` | | `User.Read,Mail.Read` | Add `Mail.ReadWrite` to enable draft tools |
23
+ | `GRAPH_TOKEN_CACHE` | | `~/.bold-tech/graph-mcp/<tenant>/tokens.json` | Per-tenant token cache |
24
+
25
+ ## Sign in (once per tenant)
26
+
27
+ ```bash
28
+ GRAPH_CLIENT_ID=… GRAPH_TENANT_ID=… npx -y @bold-tech-npm/graph-mcp login
29
+ ```
30
+
31
+ Follow the printed URL + code. Tokens cache per-tenant, so multiple clients coexist on one machine.
32
+
33
+ ## Use from an MCP client / plugin
34
+
35
+ ```json
36
+ {
37
+ "mcpServers": {
38
+ "graph": {
39
+ "command": "npx",
40
+ "args": ["-y", "@bold-tech-npm/graph-mcp"],
41
+ "env": {
42
+ "GRAPH_CLIENT_ID": "…",
43
+ "GRAPH_TENANT_ID": "…",
44
+ "GRAPH_SCOPES": "User.Read,Mail.ReadWrite"
45
+ }
46
+ }
47
+ }
48
+ }
49
+ ```
50
+
51
+ ## Tools
52
+
53
+ | Tool | Scope | Description |
54
+ |---|---|---|
55
+ | `whoami` | `User.Read` | The signed-in user (proves the auth chain) |
56
+ | `inbox_list` | `Mail.Read` | Inbox messages with unread/date filters and thread collapse |
57
+ | `create_draft` | `Mail.ReadWrite` | Create an email draft (never sends) |
58
+ | `create_reply_draft` | `Mail.ReadWrite` | Reply-draft into an existing thread (never sends) |
59
+
60
+ Draft tools require `Mail.ReadWrite` in `GRAPH_SCOPES`; with a read-only token they return a clear
61
+ permission error rather than failing silently.
package/dist/auth.js ADDED
@@ -0,0 +1,50 @@
1
+ import { PublicClientApplication } from "@azure/msal-node";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ import { getConfig } from "./config.js";
5
+ function cachePlugin(file) {
6
+ return {
7
+ beforeCacheAccess: async (ctx) => {
8
+ if (existsSync(file))
9
+ ctx.tokenCache.deserialize(readFileSync(file, "utf8"));
10
+ },
11
+ afterCacheAccess: async (ctx) => {
12
+ if (ctx.cacheHasChanged) {
13
+ mkdirSync(dirname(file), { recursive: true });
14
+ writeFileSync(file, ctx.tokenCache.serialize(), { mode: 0o600 });
15
+ }
16
+ },
17
+ };
18
+ }
19
+ function client() {
20
+ const { clientId, tenantId, cacheFile } = getConfig();
21
+ return new PublicClientApplication({
22
+ auth: { clientId, authority: `https://login.microsoftonline.com/${tenantId}` },
23
+ cache: { cachePlugin: cachePlugin(cacheFile) },
24
+ });
25
+ }
26
+ /** Interactive device-code sign-in. Caches tokens for later silent use. */
27
+ export async function deviceLogin(onMessage) {
28
+ const { scopes } = getConfig();
29
+ const result = await client().acquireTokenByDeviceCode({
30
+ scopes,
31
+ deviceCodeCallback: (r) => onMessage(r.message),
32
+ });
33
+ if (!result?.account)
34
+ throw new Error("Device-code login returned no account.");
35
+ return result.account.username;
36
+ }
37
+ /** Silent token for tool calls. Throws a clear instruction if not signed in. */
38
+ export async function getToken() {
39
+ const { scopes } = getConfig();
40
+ const pca = client();
41
+ const accounts = await pca.getTokenCache().getAllAccounts();
42
+ if (accounts.length === 0) {
43
+ throw new Error("Not signed in. Run: npx -y @bold-tech-npm/graph-mcp login (with GRAPH_CLIENT_ID and GRAPH_TENANT_ID set).");
44
+ }
45
+ const result = await pca.acquireTokenSilent({ account: accounts[0], scopes });
46
+ if (!result?.accessToken) {
47
+ throw new Error("Could not acquire a token silently — sign in again with the `login` command.");
48
+ }
49
+ return result.accessToken;
50
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @bold-tech/graph-mcp entry point.
4
+ *
5
+ * graph-mcp → run the MCP server over stdio
6
+ * graph-mcp login → interactive device-code sign-in (once per tenant)
7
+ */
8
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
9
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
10
+ import { registerTools } from "./tools.js";
11
+ import { deviceLogin } from "./auth.js";
12
+ async function main() {
13
+ if (process.argv[2] === "login") {
14
+ const user = await deviceLogin((message) => console.log(message));
15
+ console.log(`\n✓ Signed in as ${user}. Token cached — the MCP server can now run silently.`);
16
+ return;
17
+ }
18
+ const server = new McpServer({ name: "bold-tech-graph", version: "0.1.0" });
19
+ registerTools(server);
20
+ await server.connect(new StdioServerTransport());
21
+ // stderr only — stdout is the MCP channel.
22
+ console.error("[graph-mcp] running on stdio");
23
+ }
24
+ main().catch((err) => {
25
+ console.error(err instanceof Error ? err.message : err);
26
+ process.exit(1);
27
+ });
package/dist/config.js ADDED
@@ -0,0 +1,18 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ /** Read configuration from the environment. Everything is per-invocation so one
4
+ * published package can serve many tenants. */
5
+ export function getConfig() {
6
+ const clientId = process.env.GRAPH_CLIENT_ID;
7
+ const tenantId = process.env.GRAPH_TENANT_ID;
8
+ if (!clientId || !tenantId) {
9
+ throw new Error("Missing GRAPH_CLIENT_ID and/or GRAPH_TENANT_ID. Set them in the MCP server's env (see README).");
10
+ }
11
+ const scopes = (process.env.GRAPH_SCOPES ?? "User.Read,Mail.Read")
12
+ .split(",")
13
+ .map((s) => s.trim())
14
+ .filter(Boolean);
15
+ const cacheFile = process.env.GRAPH_TOKEN_CACHE ??
16
+ join(homedir(), ".bold-tech", "graph-mcp", tenantId, "tokens.json");
17
+ return { clientId, tenantId, scopes, cacheFile };
18
+ }
package/dist/graph.js ADDED
@@ -0,0 +1,19 @@
1
+ import { getToken } from "./auth.js";
2
+ const BASE = "https://graph.microsoft.com/v1.0";
3
+ /** Thin authenticated Graph fetch. Returns parsed JSON, or null for 204. */
4
+ export async function graph(path, init) {
5
+ const token = await getToken();
6
+ const res = await fetch(`${BASE}${path}`, {
7
+ ...init,
8
+ headers: {
9
+ Authorization: `Bearer ${token}`,
10
+ "Content-Type": "application/json",
11
+ ...(init?.headers ?? {}),
12
+ },
13
+ });
14
+ if (!res.ok) {
15
+ const body = (await res.text()).slice(0, 400);
16
+ throw new Error(`Graph ${init?.method ?? "GET"} ${path} -> ${res.status} ${body}`);
17
+ }
18
+ return res.status === 204 ? null : res.json();
19
+ }
package/dist/tools.js ADDED
@@ -0,0 +1,82 @@
1
+ import { z } from "zod";
2
+ import { graph } from "./graph.js";
3
+ /** Strip leading Re:/Fw:/Fwd: (and I:/R:/Aw: variants) so replies group with their thread. */
4
+ const normSubject = (s) => (s || "").replace(/^((re|fw|fwd|r|i|aw)\s*:\s*)+/i, "").trim().toLowerCase();
5
+ const text = (value) => ({
6
+ content: [{ type: "text", text: JSON.stringify(value) }],
7
+ });
8
+ export function registerTools(server) {
9
+ server.tool("whoami", "Return the signed-in Microsoft 365 user. Proves the auth chain.", {}, async () => text(await graph("/me?$select=displayName,userPrincipalName,mail")));
10
+ server.tool("inbox_list", "List Inbox messages, newest first, with optional unread and date-window filters. When collapseThreads is true (default) it returns ONE item per thread — grouping by conversationId OR normalized subject and keeping the latest message — so an overnight burst of long threads becomes a clean, deal-mappable list instead of a confusing pile.", {
11
+ unreadOnly: z.boolean().optional().describe("Only messages the user has not read yet."),
12
+ sinceHours: z
13
+ .number()
14
+ .optional()
15
+ .describe("Only messages received within the last N hours (e.g. 16 for an overnight window)."),
16
+ collapseThreads: z
17
+ .boolean()
18
+ .optional()
19
+ .describe("Collapse each thread to its latest message. Default true."),
20
+ top: z.number().optional().describe("Max messages to fetch before filtering. Default 60."),
21
+ }, async ({ unreadOnly, sinceHours, collapseThreads, top }) => {
22
+ const data = await graph(`/me/mailFolders/inbox/messages?$top=${top ?? 60}&$select=subject,from,receivedDateTime,isRead,conversationId,bodyPreview`);
23
+ let msgs = data.value ?? [];
24
+ if (unreadOnly)
25
+ msgs = msgs.filter((m) => m.isRead === false);
26
+ if (sinceHours) {
27
+ const cutoff = Date.now() - sinceHours * 3600_000;
28
+ msgs = msgs.filter((m) => Date.parse(m.receivedDateTime) >= cutoff);
29
+ }
30
+ msgs.sort((a, b) => (a.receivedDateTime < b.receivedDateTime ? 1 : -1));
31
+ if (collapseThreads === false) {
32
+ return text({ total: msgs.length, messages: msgs });
33
+ }
34
+ const byThread = new Map();
35
+ for (const m of msgs) {
36
+ const key = normSubject(m.subject) || m.conversationId || m.id;
37
+ const group = byThread.get(key);
38
+ if (group)
39
+ group.push(m);
40
+ else
41
+ byThread.set(key, [m]);
42
+ }
43
+ const threads = [...byThread.values()].map((group) => {
44
+ group.sort((a, b) => (a.receivedDateTime < b.receivedDateTime ? 1 : -1));
45
+ const latest = group[0];
46
+ return {
47
+ count: group.length,
48
+ from: latest.from?.emailAddress?.address ?? null,
49
+ subject: latest.subject,
50
+ receivedDateTime: latest.receivedDateTime,
51
+ preview: latest.bodyPreview,
52
+ messageId: latest.id,
53
+ };
54
+ });
55
+ return text({ totalMessages: msgs.length, threads: threads.length, items: threads });
56
+ });
57
+ server.tool("create_draft", "Create a new email draft in the signed-in mailbox. Requires Mail.ReadWrite. NEVER sends.", {
58
+ to: z.array(z.string()).describe("Recipient email addresses."),
59
+ subject: z.string(),
60
+ body: z.string().describe("HTML or plain-text body."),
61
+ }, async ({ to, subject, body }) => {
62
+ const draft = await graph("/me/messages", {
63
+ method: "POST",
64
+ body: JSON.stringify({
65
+ subject,
66
+ body: { contentType: "HTML", content: body },
67
+ toRecipients: to.map((address) => ({ emailAddress: { address } })),
68
+ }),
69
+ });
70
+ return text({ id: draft.id, webLink: draft.webLink });
71
+ });
72
+ server.tool("create_reply_draft", "Create a reply DRAFT to an existing message (keeps the thread). Requires Mail.ReadWrite. NEVER sends.", {
73
+ messageId: z.string().describe("The id of the message to reply to (from inbox_list)."),
74
+ comment: z.string().describe("The reply body to prepend above the quoted thread."),
75
+ }, async ({ messageId, comment }) => {
76
+ const draft = await graph(`/me/messages/${messageId}/createReply`, {
77
+ method: "POST",
78
+ body: JSON.stringify({ comment }),
79
+ });
80
+ return text({ id: draft.id, webLink: draft.webLink });
81
+ });
82
+ }
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@bold-tech-npm/graph-mcp",
3
+ "version": "0.1.0",
4
+ "description": "Microsoft Graph MCP server with device-code auth and smart inbox reads (unread + date filter, thread collapse by conversation or normalized subject). By Bold Tech.",
5
+ "type": "module",
6
+ "bin": {
7
+ "graph-mcp": "dist/cli.js"
8
+ },
9
+ "files": [
10
+ "dist",
11
+ "README.md",
12
+ "LICENSE"
13
+ ],
14
+ "scripts": {
15
+ "build": "tsc",
16
+ "prepublishOnly": "npm run build",
17
+ "login": "node dist/cli.js login"
18
+ },
19
+ "keywords": [
20
+ "mcp",
21
+ "model-context-protocol",
22
+ "microsoft-graph",
23
+ "outlook",
24
+ "m365",
25
+ "office365",
26
+ "email"
27
+ ],
28
+ "license": "MIT",
29
+ "author": "Bold Tech",
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "engines": {
34
+ "node": ">=20"
35
+ },
36
+ "dependencies": {
37
+ "@azure/msal-node": "^2.16.2",
38
+ "@modelcontextprotocol/sdk": "^1.11.0",
39
+ "zod": "^3.23.8"
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "^22.9.0",
43
+ "typescript": "^5.6.3"
44
+ }
45
+ }