@teamnetwork-nz/m365-mcp-server 1.0.6 → 1.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/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @teamnetwork-nz/m365-mcp-server
2
2
 
3
- A [Model Context Protocol (MCP)](https://modelcontextprotocol.io) server for Microsoft 365 Email and Calendar access, using **app-only (client credentials) authentication** — no user login flows required.
3
+ 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
4
 
5
- Supports multiple accounts, shared mailboxes, per-mailbox read-only access control, folder navigation, and date/content filtering. Designed to be extended with Teams support later.
5
+ Supports multiple accounts, shared mailboxes, per-mailbox read-only access control, folder navigation, date/content filtering, and grant-based SharePoint access control.
6
6
 
7
7
  ---
8
8
 
@@ -215,6 +215,74 @@ Operations always target exactly one mailbox per request, either the default or
215
215
  | `update_linked_resource` | Update a linked resource (non-readonly mailboxes only) |
216
216
  | `delete_linked_resource` | Remove a linked resource from a task (non-readonly mailboxes only) |
217
217
 
218
+ ### SharePoint
219
+
220
+ | Tool | Description |
221
+ |---|---|
222
+ | `list_sharepoint_libraries` | List configured SharePoint libraries with their grant definitions |
223
+ | `list_drive_items` | List files and folders at a path — always permitted, no grant required |
224
+ | `get_drive_item` | Get metadata for a file or folder — always permitted, no grant required |
225
+ | `check_sharepoint_access` | Check whether an operation is permitted by the grant config (no network call, never errors) — use before content operations |
226
+ | `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 |
227
+ | `upload_file` | Upload a file (base64 content, max 4 MB). Creates or overwrites. Requires `create` or `update` grant |
228
+ | `create_folder` | Create a new folder. Requires `create` grant on the parent path |
229
+ | `delete_drive_item` | Permanently delete a file or folder. Requires `delete` grant |
230
+ | `move_drive_item` | Move a file or folder, optionally renaming. Requires `update` at source and `create` at destination |
231
+ | `search_drive` | Full-text search within a library (only for libraries with `searchAllowed: true`). Results filtered by grants |
232
+
233
+ #### SharePoint grant model
234
+
235
+ Access to file content and write operations is controlled by **grants** defined per library. Each grant combines three axes — all three must match for access to be allowed:
236
+
237
+ | Axis | Description |
238
+ |---|---|
239
+ | `allowedPaths` | Which folder paths are in scope. `[]` = nothing; `["*"]` = any path; `["/Finance"]` = exact folder only; `["/Finance/*"]` = folder and all descendants |
240
+ | `allowedFiles` | Which filenames are allowed. `[]` = nothing; `["*"]` = any file; `["*.pdf", "*.xlsx"]` = glob patterns. If omitted, inherits `globalAllowedFiles` |
241
+ | `allowedOperations` | Which operations are permitted: `read`, `create`, `update`, `delete`, or `*`. If omitted, inherits `globalAllowedOperations` |
242
+
243
+ `globalAllowedFiles` and `globalAllowedOperations` are **library-level defaults** inherited by grants that omit those fields. An explicit grant value (even `[]`) always overrides the library default. The defaults are a convenience — they are not a ceiling; grants may expand beyond them.
244
+
245
+ `list_drive_items` and `get_drive_item` bypass grant evaluation entirely — always permitted.
246
+
247
+ ```json
248
+ "sharepoint": [
249
+ {
250
+ "id": "company-docs",
251
+ "displayName": "Company Documents",
252
+ "siteId": "contoso.sharepoint.com,aaa-guid,bbb-guid",
253
+ "driveId": "b!abc123...",
254
+ "searchAllowed": true,
255
+ "globalAllowedOperations": ["read"],
256
+ "globalAllowedFiles": ["*.pdf"],
257
+ "grants": [
258
+ {
259
+ "name": "Finance spreadsheets and PDFs",
260
+ "description": "Read and create Excel and PDF files in Finance and subfolders",
261
+ "allowedPaths": ["/Finance", "/Finance/*"],
262
+ "allowedFiles": ["*.xlsx", "*.pdf"],
263
+ "allowedOperations": ["read", "create"]
264
+ },
265
+ {
266
+ "name": "Reports PDFs (inherited defaults)",
267
+ "description": "Read-only PDF access in /Reports — inherits globalAllowedFiles and globalAllowedOperations",
268
+ "allowedPaths": ["/Reports", "/Reports/*"]
269
+ }
270
+ ]
271
+ }
272
+ ]
273
+ ```
274
+
275
+ #### Finding your siteId and driveId
276
+
277
+ You can find these values in the [Azure Portal](https://portal.azure.com) → SharePoint admin centre, or by making a Graph API call:
278
+
279
+ ```
280
+ GET https://graph.microsoft.com/v1.0/sites/{hostname}:/sites/{sitePath}
281
+ GET https://graph.microsoft.com/v1.0/sites/{siteId}/drives
282
+ ```
283
+
284
+ The `siteId` has the format `hostname,site-guid,web-guid`. The `driveId` is the `id` field on the default document library drive.
285
+
218
286
  ---
219
287
 
220
288
  ## Admin Setup
@@ -239,6 +307,8 @@ Grant the following **Application permissions** (not Delegated) and click **Gran
239
307
  | `Calendars.Read` | Reading calendar events |
240
308
  | `Calendars.ReadWrite` | Creating and updating events |
241
309
  | `Tasks.ReadWrite.All` | Reading and writing To Do lists and tasks |
310
+ | `Sites.Read.All` | Reading SharePoint sites, drives, and file metadata |
311
+ | `Sites.ReadWrite.All` | Uploading files, creating folders, deleting, and moving items in SharePoint |
242
312
 
243
313
  ### 2. Restrict Mailbox Access (Recommended)
244
314
 
@@ -23,5 +23,53 @@
23
23
  { "email": "partner@other.com", "readonly": false }
24
24
  ]
25
25
  }
26
+ ],
27
+ "sharepoint": [
28
+ {
29
+ "id": "company-docs",
30
+ "displayName": "Company Documents",
31
+ "siteId": "contoso.sharepoint.com,aaa-guid-here,bbb-guid-here",
32
+ "driveId": "b!abc123driveIdHere",
33
+ "searchAllowed": true,
34
+ "globalAllowedOperations": ["read"],
35
+ "globalAllowedFiles": ["*.pdf"],
36
+ "grants": [
37
+ {
38
+ "name": "Finance spreadsheets and PDFs",
39
+ "description": "Read and create Excel and PDF files in the Finance folder and all subfolders",
40
+ "allowedPaths": ["/Finance", "/Finance/*"],
41
+ "allowedFiles": ["*.xlsx", "*.pdf"],
42
+ "allowedOperations": ["read", "create"]
43
+ },
44
+ {
45
+ "name": "Reports PDFs (inherited defaults)",
46
+ "description": "Read-only access to PDF files in /Reports — inherits globalAllowedFiles and globalAllowedOperations from the library",
47
+ "allowedPaths": ["/Reports", "/Reports/*"]
48
+ },
49
+ {
50
+ "name": "Public folder full access",
51
+ "description": "Unrestricted access to all files under the Public folder",
52
+ "allowedPaths": ["/Public/*"],
53
+ "allowedFiles": ["*"],
54
+ "allowedOperations": ["*"]
55
+ }
56
+ ]
57
+ },
58
+ {
59
+ "id": "hr-library",
60
+ "displayName": "HR Policies",
61
+ "siteId": "contoso.sharepoint.com,ccc-guid-here,ddd-guid-here",
62
+ "driveId": "b!xyz789driveIdHere",
63
+ "searchAllowed": false,
64
+ "globalAllowedOperations": ["read"],
65
+ "globalAllowedFiles": ["*.pdf"],
66
+ "grants": [
67
+ {
68
+ "name": "HR policy documents",
69
+ "description": "Download PDF policy documents from any HR folder — operations and files inherited from library defaults",
70
+ "allowedPaths": ["*"]
71
+ }
72
+ ]
73
+ }
26
74
  ]
27
75
  }
@@ -17,7 +17,37 @@ export const AccountConfigSchema = z.object({
17
17
  clientSecret: z.string().min(1).optional(),
18
18
  mailboxes: z.array(MailboxConfigSchema).min(1, 'Each account must have at least one mailbox'),
19
19
  });
20
+ // ── SharePoint ──────────────────────────────────────────────────────────────
21
+ const SHAREPOINT_OPS = ['read', 'create', 'update', 'delete', '*'];
22
+ const validOps = (ops) => ops.every((o) => SHAREPOINT_OPS.includes(o));
23
+ const opsMessage = 'values must be one of: read, create, update, delete, *';
24
+ export const SharepointGrantSchema = z.object({
25
+ name: z.string().optional(),
26
+ description: z.string().optional(),
27
+ allowedPaths: z.array(z.string()),
28
+ allowedFiles: z.array(z.string()).optional(),
29
+ allowedOperations: z
30
+ .array(z.string())
31
+ .optional()
32
+ .refine((ops) => ops === undefined || validOps(ops), {
33
+ message: `grant.allowedOperations ${opsMessage}`,
34
+ }),
35
+ });
36
+ export const SharepointLibraryConfigSchema = z.object({
37
+ id: z.string().min(1, 'sharepoint library id must not be empty'),
38
+ displayName: z.string().optional(),
39
+ siteId: z.string().min(1, 'siteId must not be empty'),
40
+ driveId: z.string().min(1, 'driveId must not be empty'),
41
+ searchAllowed: z.boolean().default(false),
42
+ globalAllowedOperations: z
43
+ .array(z.string())
44
+ .refine(validOps, { message: `globalAllowedOperations ${opsMessage}` }),
45
+ globalAllowedFiles: z.array(z.string()),
46
+ grants: z.array(SharepointGrantSchema),
47
+ });
48
+ // ── Root config ─────────────────────────────────────────────────────────────
20
49
  export const AppConfigSchema = z.object({
21
50
  connection: ConnectionConfigSchema,
22
51
  accounts: z.array(AccountConfigSchema).min(1, 'Config must have at least one account'),
52
+ sharepoint: z.array(SharepointLibraryConfigSchema).optional(),
23
53
  });
@@ -0,0 +1,120 @@
1
+ import { ResponseType } from '@microsoft/microsoft-graph-client';
2
+ import { mapGraphError } from '../utils/errors.js';
3
+ import { buildDrivePath } from '../utils/pathUtils.js';
4
+ const ITEM_SELECT = 'id,name,file,folder,size,createdDateTime,lastModifiedDateTime,webUrl,parentReference';
5
+ // ── Directory / metadata ────────────────────────────────────────────────────
6
+ export async function listDriveItems(client, driveId, path) {
7
+ try {
8
+ const base = buildDrivePath(driveId, path);
9
+ // root is /drives/{id}/root — append /children directly
10
+ // non-root is /drives/{id}/root:/{path} — append :/children
11
+ const url = path === '/' || path === ''
12
+ ? `${base}/children`
13
+ : `${base}:/children`;
14
+ return await client.api(url).select(ITEM_SELECT).get();
15
+ }
16
+ catch (err) {
17
+ throw mapGraphError(err, 'list_drive_items');
18
+ }
19
+ }
20
+ export async function getDriveItem(client, driveId, path) {
21
+ try {
22
+ const url = buildDrivePath(driveId, path);
23
+ return await client.api(url).get();
24
+ }
25
+ catch (err) {
26
+ throw mapGraphError(err, 'get_drive_item');
27
+ }
28
+ }
29
+ // ── File content ────────────────────────────────────────────────────────────
30
+ export async function downloadFile(client, driveId, path) {
31
+ try {
32
+ const url = `${buildDrivePath(driveId, path)}:/content`;
33
+ return (await client
34
+ .api(url)
35
+ .responseType(ResponseType.ARRAYBUFFER)
36
+ .get());
37
+ }
38
+ catch (err) {
39
+ throw mapGraphError(err, 'download_file');
40
+ }
41
+ }
42
+ export async function uploadFile(client, driveId, path, content, contentType) {
43
+ try {
44
+ const url = `${buildDrivePath(driveId, path)}:/content`;
45
+ return await client
46
+ .api(url)
47
+ .header('Content-Type', contentType)
48
+ .put(content);
49
+ }
50
+ catch (err) {
51
+ throw mapGraphError(err, 'upload_file');
52
+ }
53
+ }
54
+ // ── Write operations ────────────────────────────────────────────────────────
55
+ export async function createFolder(client, driveId, parentPath, folderName) {
56
+ try {
57
+ const base = buildDrivePath(driveId, parentPath);
58
+ const url = parentPath === '/' || parentPath === ''
59
+ ? `${base}/children`
60
+ : `${base}:/children`;
61
+ return await client.api(url).post({
62
+ name: folderName,
63
+ folder: {},
64
+ '@microsoft.graph.conflictBehavior': 'fail',
65
+ });
66
+ }
67
+ catch (err) {
68
+ throw mapGraphError(err, 'create_folder');
69
+ }
70
+ }
71
+ export async function deleteDriveItem(client, driveId, path) {
72
+ try {
73
+ const url = buildDrivePath(driveId, path);
74
+ await client.api(url).delete();
75
+ }
76
+ catch (err) {
77
+ throw mapGraphError(err, 'delete_drive_item');
78
+ }
79
+ }
80
+ export async function moveDriveItem(client, driveId, sourcePath, destFolderPath, newName) {
81
+ try {
82
+ // Resolve source item ID
83
+ const sourceItem = (await client
84
+ .api(buildDrivePath(driveId, sourcePath))
85
+ .select('id')
86
+ .get());
87
+ // Resolve destination folder ID
88
+ const destItem = (await client
89
+ .api(buildDrivePath(driveId, destFolderPath))
90
+ .select('id')
91
+ .get());
92
+ const patch = {
93
+ parentReference: { id: destItem.id },
94
+ };
95
+ if (newName !== undefined)
96
+ patch['name'] = newName;
97
+ return await client.api(`/drives/${driveId}/items/${sourceItem.id}`).patch(patch);
98
+ }
99
+ catch (err) {
100
+ throw mapGraphError(err, 'move_drive_item');
101
+ }
102
+ }
103
+ export async function searchDrive(client, driveId, query, scopePath, maxResults) {
104
+ try {
105
+ // OData single-quote escape
106
+ const oq = query.replace(/'/g, "''");
107
+ const url = scopePath && scopePath !== '/'
108
+ ? `${buildDrivePath(driveId, scopePath)}:/search(q='${oq}')`
109
+ : `/drives/${driveId}/root/search(q='${oq}')`;
110
+ const result = (await client
111
+ .api(url)
112
+ .select('id,name,file,folder,size,webUrl,parentReference')
113
+ .top(maxResults)
114
+ .get());
115
+ return result.value ?? [];
116
+ }
117
+ catch (err) {
118
+ throw mapGraphError(err, 'search_drive');
119
+ }
120
+ }
@@ -13,9 +13,10 @@ const TASK_SELECT = [
13
13
  ].join(',');
14
14
  export async function listTodoLists(client, email) {
15
15
  try {
16
+ // Note: the To Do lists endpoint has limited $select support with app-only auth.
17
+ // Fetch without $select to get all available fields rather than risk a 400.
16
18
  return await client
17
19
  .api(`/users/${email}/todo/lists`)
18
- .select('id,displayName,isOwner,isShared,wellknownListName')
19
20
  .get();
20
21
  }
21
22
  catch (err) {
@@ -29,11 +30,12 @@ export async function listTodoTasks(client, email, listId, params) {
29
30
  filters.push(`status eq '${params.status}'`);
30
31
  if (params.importance !== undefined)
31
32
  filters.push(`importance eq '${params.importance}'`);
33
+ // Note: the To Do tasks endpoint has limited $select support with app-only auth.
34
+ // Fetch without $select to avoid a 400, same as listTodoLists.
35
+ // $orderby is also unsupported with app-only auth.
32
36
  let req = client
33
37
  .api(`/users/${email}/todo/lists/${listId}/tasks`)
34
- .select(TASK_SELECT)
35
- .top(params.maxResults)
36
- .orderby('lastModifiedDateTime desc');
38
+ .top(params.maxResults);
37
39
  if (filters.length > 0) {
38
40
  req = req.filter(filters.join(' and '));
39
41
  }
package/dist/index.js CHANGED
@@ -16,7 +16,36 @@ async function main() {
16
16
  // 3. Create MCP server and register all tools
17
17
  const server = new McpServer({
18
18
  name: '@teamnetwork/m365-mcp-server',
19
- version: '1.0.0',
19
+ version: '1.0.7',
20
+ }, {
21
+ instructions: `
22
+ Microsoft 365 MCP server — email, calendar, and To Do via the Microsoft Graph API.
23
+
24
+ ## Accounts and mailboxes
25
+ - Most tools accept optional accountId and mailbox parameters. Omit both to use the first configured account and its first mailbox.
26
+ - Call list_mailboxes once at the start of a session if you need to work with a specific account or mailbox, or if a tool returns a CONFIG_ERROR.
27
+ - Some mailboxes are marked read-only in config. Write tools (send_message, create_event, create_todo_task, etc.) will fail with READONLY_VIOLATION on those mailboxes — do not retry, report the error to the user.
28
+
29
+ ## Datetime handling
30
+ - All datetime inputs accept naive local time ("2026-05-11T09:00:00") or explicit offset ("2026-05-11T09:00:00+12:00").
31
+ - Naive strings are interpreted as the server's configured timezone (DATETIME_FORMAT env var — typically the user's local timezone). Do not convert to UTC before passing.
32
+ - All datetime values in responses are already expressed in the configured local timezone with offset (e.g. "2026-05-11T09:00:00+12:00"). Present these to the user as-is.
33
+
34
+ ## Email
35
+ - list_messages returns metadata only (subject, sender, preview). Call get_message with the messageId to retrieve the full body.
36
+ - The bodySearch parameter performs a full-text search but cannot be combined with server-side filters (startDate, endDate, sender). When bodySearch is used, those filters are applied client-side after retrieval.
37
+ - Use list_folders to discover folder IDs. Well-known names ("Inbox", "SentItems", "Drafts", "DeletedItems", "JunkEmail") work without a lookup.
38
+
39
+ ## Calendar
40
+ - list_events requires both startDate and endDate and expands recurring events within that window.
41
+ - Call list_calendars to discover calendarId values. Omit calendarId to use the default calendar.
42
+
43
+ ## To Do
44
+ - All To Do task operations require a listId. Always call list_todo_lists first to discover available lists and their IDs.
45
+ - list_todo_tasks defaults to returning all statuses. Pass status="notStarted" to see only open tasks.
46
+ - 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
+ - delete_todo_task is permanent and irreversible. Confirm with the user before calling it.
48
+ `.trim(),
20
49
  });
21
50
  registerAllTools(server, config, auth);
22
51
  // 4. Connect via stdio transport (Claude Desktop / Claude Code)
@@ -0,0 +1,209 @@
1
+ /**
2
+ * SharePoint access guard — grant-based permission evaluation.
3
+ *
4
+ * ## Access control model
5
+ *
6
+ * Each SharePoint library has an array of grants. A grant has three axes:
7
+ *
8
+ * allowedPaths — which folder paths are in scope (required per grant)
9
+ * allowedFiles — which filenames/globs are in scope (optional)
10
+ * allowedOperations — which operations are permitted (optional)
11
+ *
12
+ * When `allowedFiles` or `allowedOperations` are omitted from a grant, the
13
+ * library-level defaults (`globalAllowedFiles`, `globalAllowedOperations`) are
14
+ * inherited. An explicit value on the grant — even `[]` — always overrides the
15
+ * library global.
16
+ *
17
+ * ## Evaluation
18
+ *
19
+ * For a file operation:
20
+ * Access is ALLOWED if any single grant satisfies ALL THREE of:
21
+ * pathMatchesGrant(folderPath, grant.allowedPaths)
22
+ * fileMatchesGrant(filename, effectiveAllowedFiles)
23
+ * operationMatchesGrant(op, effectiveAllowedOperations)
24
+ *
25
+ * For a folder operation (create_folder, delete folder, move folder):
26
+ * allowedFiles is NOT evaluated — only path and operation are checked.
27
+ *
28
+ * ## Directory/metadata operations
29
+ *
30
+ * list_drive_items and get_drive_item bypass this guard entirely and are
31
+ * always permitted regardless of grant configuration.
32
+ *
33
+ * ## Operations
34
+ *
35
+ * read — download_file
36
+ * create — upload_file (new file), create_folder
37
+ * update — upload_file (overwrite existing), move_drive_item (source side)
38
+ * delete — delete_drive_item
39
+ *
40
+ * upload_file requires "create" OR "update" in effective ops.
41
+ * move_drive_item requires "update" at source AND "create" at destination.
42
+ *
43
+ * ## Path patterns
44
+ *
45
+ * [] — nothing (grant never fires)
46
+ * ["*"] — any path
47
+ * ["/A"] — /A only, NOT /A/child
48
+ * ["/A/*"] — /A and all descendants
49
+ *
50
+ * Trailing /* is the ONLY way to grant recursive access.
51
+ * All path comparisons are case-insensitive.
52
+ *
53
+ * ## File patterns (glob)
54
+ *
55
+ * [] — nothing
56
+ * ["*"] — any filename
57
+ * ["*.pdf"] — extension glob
58
+ * ["report_*.*"] — prefix glob
59
+ * ["exact.csv"] — exact match
60
+ *
61
+ * * matches any sequence of characters (not path separators).
62
+ * All file comparisons are case-insensitive.
63
+ */
64
+ import { ToolError } from '../utils/errors.js';
65
+ import { normalisePath } from '../utils/pathUtils.js';
66
+ // ── Pattern matching ────────────────────────────────────────────────────────
67
+ /**
68
+ * Test whether a normalised folder path matches any pattern in allowedPaths.
69
+ *
70
+ * Pattern semantics (case-insensitive):
71
+ * * → any path
72
+ * /Finance → exact match (children not included)
73
+ * /Finance/* → /Finance and all descendants
74
+ */
75
+ function pathMatchesGrant(folderPath, allowedPaths) {
76
+ if (allowedPaths.length === 0)
77
+ return false;
78
+ const np = normalisePath(folderPath);
79
+ for (const pattern of allowedPaths) {
80
+ const lp = pattern.toLowerCase().trim();
81
+ if (lp === '*')
82
+ return true;
83
+ if (lp.endsWith('/*')) {
84
+ // Recursive: /Finance/* → matches /Finance and /Finance/...
85
+ const base = normalisePath(lp.slice(0, -2)); // strip /*
86
+ if (np === base || np.startsWith(base + '/'))
87
+ return true;
88
+ }
89
+ else {
90
+ // Exact folder match
91
+ if (np === normalisePath(lp))
92
+ return true;
93
+ }
94
+ }
95
+ return false;
96
+ }
97
+ /**
98
+ * Test whether a filename matches any glob pattern in allowedFiles.
99
+ *
100
+ * Glob semantics (case-insensitive):
101
+ * * — matches any sequence of characters (excluding path separators)
102
+ */
103
+ function fileMatchesGrant(filename, allowedFiles) {
104
+ if (allowedFiles.length === 0)
105
+ return false;
106
+ const lf = filename.toLowerCase();
107
+ for (const pattern of allowedFiles) {
108
+ const lp = pattern.toLowerCase().trim();
109
+ if (lp === '*')
110
+ return true;
111
+ // Glob → regex: escape regex metacharacters except *, then replace * with .*
112
+ const regexStr = lp
113
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&') // escape special chars (not *)
114
+ .replace(/\*/g, '.*'); // * → .*
115
+ if (new RegExp(`^${regexStr}$`).test(lf))
116
+ return true;
117
+ }
118
+ return false;
119
+ }
120
+ /**
121
+ * Test whether the requested operation is permitted by allowedOperations.
122
+ * ["*"] grants all operations.
123
+ */
124
+ function operationMatchesGrant(op, allowedOps) {
125
+ if (allowedOps.length === 0)
126
+ return false;
127
+ if (allowedOps.includes('*'))
128
+ return true;
129
+ return allowedOps.includes(op);
130
+ }
131
+ // ── Evaluation ──────────────────────────────────────────────────────────────
132
+ /**
133
+ * Evaluate file access: all three axes (path, file, operation) must match
134
+ * within a single grant using effective inherited values.
135
+ */
136
+ export function evaluateFileAccess(library, folderPath, filename, operation) {
137
+ for (let i = 0; i < library.grants.length; i++) {
138
+ const grant = library.grants[i];
139
+ const effectiveFiles = grant.allowedFiles ?? library.globalAllowedFiles;
140
+ const effectiveOps = grant.allowedOperations ?? library.globalAllowedOperations;
141
+ if (pathMatchesGrant(folderPath, grant.allowedPaths) &&
142
+ fileMatchesGrant(filename, effectiveFiles) &&
143
+ operationMatchesGrant(operation, effectiveOps)) {
144
+ return {
145
+ allowed: true,
146
+ reason: `Access permitted by grant${grant.name ? ` "${grant.name}"` : ` #${i}`}.`,
147
+ matchedGrantIndex: i,
148
+ ...(grant.name !== undefined && { matchedGrantName: grant.name }),
149
+ ...(grant.description !== undefined && { matchedGrantDescription: grant.description }),
150
+ };
151
+ }
152
+ }
153
+ return {
154
+ allowed: false,
155
+ reason: `Access denied: no grant in library "${library.id}" permits ${operation} on ` +
156
+ `"${folderPath}/${filename}". Use check_sharepoint_access to inspect the grant configuration.`,
157
+ };
158
+ }
159
+ /**
160
+ * Evaluate folder access: only path and operation are checked.
161
+ * allowedFiles / globalAllowedFiles are NOT evaluated for folder operations.
162
+ */
163
+ export function evaluateFolderAccess(library, folderPath, operation) {
164
+ for (let i = 0; i < library.grants.length; i++) {
165
+ const grant = library.grants[i];
166
+ const effectiveOps = grant.allowedOperations ?? library.globalAllowedOperations;
167
+ if (pathMatchesGrant(folderPath, grant.allowedPaths) &&
168
+ operationMatchesGrant(operation, effectiveOps)) {
169
+ return {
170
+ allowed: true,
171
+ reason: `Access permitted by grant${grant.name ? ` "${grant.name}"` : ` #${i}`}.`,
172
+ matchedGrantIndex: i,
173
+ ...(grant.name !== undefined && { matchedGrantName: grant.name }),
174
+ ...(grant.description !== undefined && { matchedGrantDescription: grant.description }),
175
+ };
176
+ }
177
+ }
178
+ return {
179
+ allowed: false,
180
+ reason: `Access denied: no grant in library "${library.id}" permits ${operation} on ` +
181
+ `folder "${folderPath}". Use check_sharepoint_access to inspect the grant configuration.`,
182
+ };
183
+ }
184
+ /**
185
+ * Check whether a folder path falls within any configured grant's allowedPaths.
186
+ * No file or operation check — purely a path scope test.
187
+ *
188
+ * Used by search_drive to distinguish:
189
+ * - Path in scope, file not accessible → restrictedMatchCount (user knows the folder)
190
+ * - Path not in scope at all → silent drop (no information revealed)
191
+ */
192
+ export function pathIsConfigured(library, folderPath) {
193
+ return library.grants.some((grant) => pathMatchesGrant(folderPath, grant.allowedPaths));
194
+ }
195
+ // ── Asserting guards (throw on deny) ────────────────────────────────────────
196
+ /** Throws ToolError('ACCESS_DENIED') if file access is not permitted. */
197
+ export function assertFileAccess(library, folderPath, filename, operation) {
198
+ const result = evaluateFileAccess(library, folderPath, filename, operation);
199
+ if (!result.allowed) {
200
+ throw new ToolError(result.reason, 'ACCESS_DENIED');
201
+ }
202
+ }
203
+ /** Throws ToolError('ACCESS_DENIED') if folder access is not permitted. */
204
+ export function assertFolderAccess(library, folderPath, operation) {
205
+ const result = evaluateFolderAccess(library, folderPath, operation);
206
+ if (!result.allowed) {
207
+ throw new ToolError(result.reason, 'ACCESS_DENIED');
208
+ }
209
+ }
@@ -26,6 +26,17 @@ import { registerGetLinkedResource } from './todo/getLinkedResource.js';
26
26
  import { registerCreateLinkedResource } from './todo/createLinkedResource.js';
27
27
  import { registerUpdateLinkedResource } from './todo/updateLinkedResource.js';
28
28
  import { registerDeleteLinkedResource } from './todo/deleteLinkedResource.js';
29
+ // SharePoint tools
30
+ import { registerListSharepointLibraries } from './sharepoint/listSharepointLibraries.js';
31
+ import { registerListDriveItems } from './sharepoint/listDriveItems.js';
32
+ import { registerGetDriveItem } from './sharepoint/getDriveItem.js';
33
+ import { registerCheckSharepointAccess } from './sharepoint/checkSharepointAccess.js';
34
+ import { registerDownloadFile } from './sharepoint/downloadFile.js';
35
+ import { registerUploadFile } from './sharepoint/uploadFile.js';
36
+ import { registerCreateFolder } from './sharepoint/createFolder.js';
37
+ import { registerDeleteDriveItem } from './sharepoint/deleteDriveItem.js';
38
+ import { registerMoveDriveItem } from './sharepoint/moveDriveItem.js';
39
+ import { registerSearchDrive } from './sharepoint/searchDrive.js';
29
40
  function registerEmailTools(server, config, auth) {
30
41
  registerListMailboxes(server, config);
31
42
  registerListFolders(server, config, auth);
@@ -57,9 +68,30 @@ function registerTodoTools(server, config, auth) {
57
68
  registerUpdateLinkedResource(server, config, auth);
58
69
  registerDeleteLinkedResource(server, config, auth);
59
70
  }
71
+ function registerSharepointTools(server, config, auth) {
72
+ if (!config.sharepoint || config.sharepoint.length === 0)
73
+ return;
74
+ registerListSharepointLibraries(server, config);
75
+ registerListDriveItems(server, config, auth);
76
+ registerGetDriveItem(server, config, auth);
77
+ registerCheckSharepointAccess(server, config);
78
+ registerDownloadFile(server, config, auth);
79
+ registerUploadFile(server, config, auth);
80
+ registerCreateFolder(server, config, auth);
81
+ registerDeleteDriveItem(server, config, auth);
82
+ registerMoveDriveItem(server, config, auth);
83
+ // search_drive is only registered when at least one library has searchAllowed: true.
84
+ // The handler checks library.searchAllowed at call time and returns SEARCH_NOT_ENABLED
85
+ // if the specific library isn't enabled — this lets the tool be discoverable while still
86
+ // gating per-library.
87
+ if (config.sharepoint.some((lib) => lib.searchAllowed)) {
88
+ registerSearchDrive(server, config, auth);
89
+ }
90
+ }
60
91
  export function registerAllTools(server, config, auth) {
61
92
  registerEmailTools(server, config, auth);
62
93
  registerCalendarTools(server, config, auth);
63
94
  registerTodoTools(server, config, auth);
95
+ registerSharepointTools(server, config, auth);
64
96
  // Future: registerTeamsTools(server, config, auth);
65
97
  }