@teamnetwork-nz/m365-mcp-server 1.0.7 → 1.1.1

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`). Only results passing all three grant axes (path + file + operation) are returned — everything else is silently dropped |
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
+ }
@@ -0,0 +1,198 @@
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
+ // ── Asserting guards (throw on deny) ────────────────────────────────────────
185
+ /** Throws ToolError('ACCESS_DENIED') if file access is not permitted. */
186
+ export function assertFileAccess(library, folderPath, filename, operation) {
187
+ const result = evaluateFileAccess(library, folderPath, filename, operation);
188
+ if (!result.allowed) {
189
+ throw new ToolError(result.reason, 'ACCESS_DENIED');
190
+ }
191
+ }
192
+ /** Throws ToolError('ACCESS_DENIED') if folder access is not permitted. */
193
+ export function assertFolderAccess(library, folderPath, operation) {
194
+ const result = evaluateFolderAccess(library, folderPath, operation);
195
+ if (!result.allowed) {
196
+ throw new ToolError(result.reason, 'ACCESS_DENIED');
197
+ }
198
+ }
@@ -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
  }
@@ -127,6 +127,97 @@ export const UpdateTodoTaskSchema = TodoBase.extend({
127
127
  export const DeleteTodoTaskSchema = TodoBase.extend({
128
128
  taskId: z.string().describe('The task ID to delete'),
129
129
  });
130
+ // ── SharePoint tools ───────────────────────────────────────────────────────
131
+ //
132
+ // Access control model (see src/middleware/sharepointGuard.ts for full docs):
133
+ //
134
+ // Each library has an array of grants. Each grant has three axes:
135
+ // allowedPaths — folder paths in scope (required per grant)
136
+ // allowedFiles — filename globs in scope (inherits globalAllowedFiles if omitted)
137
+ // allowedOperations — permitted ops (inherits globalAllowedOperations if omitted)
138
+ //
139
+ // Access is allowed when ALL THREE axes match within a SINGLE grant.
140
+ //
141
+ // Operations: read (download), create (new file/folder), update (overwrite/move), delete
142
+ // Path rules: ["/A"] = /A only; ["/A/*"] = /A and all descendants; ["*"] = any path
143
+ // File rules: ["*.pdf"] = glob, case-insensitive; ["*"] = any file
144
+ //
145
+ // list_drive_items and get_drive_item are ALWAYS permitted — no grant required.
146
+ // Use check_sharepoint_access to evaluate permissions before attempting an operation.
147
+ const SharepointBase = z.object({
148
+ libraryId: z
149
+ .string()
150
+ .describe('SharePoint library ID as configured. Use list_sharepoint_libraries to discover available IDs.'),
151
+ });
152
+ export const ListSharepointLibrariesSchema = z.object({});
153
+ export const ListDriveItemsSchema = SharepointBase.extend({
154
+ path: z
155
+ .string()
156
+ .default('/')
157
+ .describe('Folder path within the library (e.g. "/Finance/Reports"). Defaults to root. Always permitted — no grant required.'),
158
+ });
159
+ export const GetDriveItemSchema = SharepointBase.extend({
160
+ path: z.string().describe('Path to the file or folder (e.g. "/Finance/Reports/Q1.pdf"). Always permitted — no grant required.'),
161
+ });
162
+ export const CheckSharepointAccessSchema = SharepointBase.extend({
163
+ folderPath: z
164
+ .string()
165
+ .describe('The folder/directory portion of the path (e.g. "/Finance/Reports"). ' +
166
+ 'For a file at /Finance/Reports/Q1.pdf, folderPath is /Finance/Reports.'),
167
+ filename: z
168
+ .string()
169
+ .optional()
170
+ .describe('The filename to check (e.g. "Q1.pdf"). ' +
171
+ 'Omit to perform a folder-level check only (allowedFiles is not evaluated).'),
172
+ operation: z
173
+ .enum(['read', 'create', 'update', 'delete'])
174
+ .default('read')
175
+ .describe('Operation to check. ' +
176
+ 'read = download_file; ' +
177
+ 'create = upload_file (new) or create_folder; ' +
178
+ 'update = upload_file (overwrite) or move_drive_item source; ' +
179
+ 'delete = delete_drive_item.'),
180
+ });
181
+ export const DownloadFileSchema = SharepointBase.extend({
182
+ path: z
183
+ .string()
184
+ .describe('Full path to the file to download (e.g. "/Finance/Reports/Q1.pdf"). ' +
185
+ 'Requires a grant with "read" in allowedOperations for this path and file.'),
186
+ });
187
+ export const UploadFileSchema = SharepointBase.extend({
188
+ path: z
189
+ .string()
190
+ .describe('Full destination path including filename (e.g. "/Finance/Reports/Q1.pdf"). ' +
191
+ 'Requires a grant with "create" OR "update" in allowedOperations.'),
192
+ content: z.string().describe('Base64-encoded file content. Maximum 4 MB.'),
193
+ contentType: z
194
+ .string()
195
+ .default('application/octet-stream')
196
+ .describe('MIME type of the file (e.g. "application/pdf", "image/png").'),
197
+ });
198
+ export const CreateFolderSchema = SharepointBase.extend({
199
+ parentPath: z
200
+ .string()
201
+ .default('/')
202
+ .describe('Parent folder path (e.g. "/Finance"). Defaults to root.'),
203
+ folderName: z.string().min(1).describe('Name of the new folder.'),
204
+ });
205
+ export const DeleteDriveItemSchema = SharepointBase.extend({
206
+ path: z.string().describe('Path to the file or folder to permanently delete.'),
207
+ });
208
+ export const MoveDriveItemSchema = SharepointBase.extend({
209
+ sourcePath: z.string().describe('Current path of the file or folder to move.'),
210
+ destFolderPath: z.string().describe('Destination folder path. The item will be placed inside this folder.'),
211
+ newName: z.string().optional().describe('New name for the item after moving. Omit to keep the original name.'),
212
+ });
213
+ export const SearchDriveSchema = SharepointBase.extend({
214
+ query: z.string().min(1).describe('Full-text search query. Uses Microsoft Graph drive search.'),
215
+ scopePath: z
216
+ .string()
217
+ .optional()
218
+ .describe('Scope the search to a specific folder (e.g. "/Finance"). Omit to search the entire library.'),
219
+ maxResults: z.number().int().min(1).max(100).default(25),
220
+ });
130
221
  // ── Linked Resource tools ──────────────────────────────────────────────────
131
222
  const TaskBase = TodoBase.extend({
132
223
  taskId: z.string().describe('The task ID'),
@@ -0,0 +1,34 @@
1
+ import { CheckSharepointAccessSchema } from '../schemas.js';
2
+ import { evaluateFileAccess, evaluateFolderAccess } from '../../middleware/sharepointGuard.js';
3
+ import { errorResponse } from '../../utils/errors.js';
4
+ import { logger } from '../../utils/logger.js';
5
+ import { resolveSharepointLibrary } from '../../utils/resolveSharepointLibrary.js';
6
+ export function registerCheckSharepointAccess(server, config) {
7
+ server.tool('check_sharepoint_access', 'Check whether a file or folder operation is permitted by the library grant configuration. ' +
8
+ 'Does NOT make any network calls — evaluates config only. Never throws an error. ' +
9
+ 'Returns { allowed, reason } and, when allowed, the matched grant name and description. ' +
10
+ '\n\nUse this tool BEFORE attempting download_file, upload_file, delete_drive_item, or ' +
11
+ 'move_drive_item to give the user a clear explanation if access would be denied. ' +
12
+ '\n\nNote: list_drive_items and get_drive_item are always permitted regardless of grants ' +
13
+ 'and do not need to be checked here.', CheckSharepointAccessSchema.shape, async (params) => {
14
+ try {
15
+ const library = resolveSharepointLibrary(config, params.libraryId);
16
+ logger.info('check_sharepoint_access', {
17
+ libraryId: library.id,
18
+ folderPath: params.folderPath,
19
+ filename: params.filename,
20
+ operation: params.operation,
21
+ });
22
+ const operation = params.operation;
23
+ const result = params.filename
24
+ ? evaluateFileAccess(library, params.folderPath, params.filename, operation)
25
+ : evaluateFolderAccess(library, params.folderPath, operation);
26
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
27
+ }
28
+ catch (err) {
29
+ // resolveSharepointLibrary may throw CONFIG_ERROR — surface it normally
30
+ logger.error('check_sharepoint_access failed', { libraryId: params.libraryId });
31
+ return errorResponse(err);
32
+ }
33
+ });
34
+ }
@@ -0,0 +1,26 @@
1
+ import { CreateFolderSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { createFolder } from '../../graph/sharepoint.js';
4
+ import { assertFolderAccess } from '../../middleware/sharepointGuard.js';
5
+ import { errorResponse } from '../../utils/errors.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ import { resolveSharepointLibrary } from '../../utils/resolveSharepointLibrary.js';
8
+ export function registerCreateFolder(server, config, auth) {
9
+ server.tool('create_folder', 'Create a new folder in a SharePoint document library. ' +
10
+ 'Requires a grant with "create" in allowedOperations for the parent path. ' +
11
+ 'Returns the created folder metadata. Fails if a folder with that name already exists.', CreateFolderSchema.shape, async (params) => {
12
+ try {
13
+ const library = resolveSharepointLibrary(config, params.libraryId);
14
+ logger.info('create_folder', { libraryId: library.id, parentPath: params.parentPath, folderName: params.folderName });
15
+ assertFolderAccess(library, params.parentPath, 'create');
16
+ const token = await auth.getAccessToken(config.accounts[0].id);
17
+ const client = createGraphClient(token);
18
+ const result = await createFolder(client, library.driveId, params.parentPath, params.folderName);
19
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
20
+ }
21
+ catch (err) {
22
+ logger.error('create_folder failed', { libraryId: params.libraryId });
23
+ return errorResponse(err);
24
+ }
25
+ });
26
+ }
@@ -0,0 +1,48 @@
1
+ import { DeleteDriveItemSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { getDriveItem, deleteDriveItem } from '../../graph/sharepoint.js';
4
+ import { assertFileAccess, assertFolderAccess } from '../../middleware/sharepointGuard.js';
5
+ import { errorResponse } from '../../utils/errors.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ import { resolveSharepointLibrary } from '../../utils/resolveSharepointLibrary.js';
8
+ import { splitPath } from '../../utils/pathUtils.js';
9
+ export function registerDeleteDriveItem(server, config, auth) {
10
+ server.tool('delete_drive_item', 'Permanently delete a file or folder from a SharePoint document library. ' +
11
+ 'For files, requires a grant with "delete" in allowedOperations for the file path and filename. ' +
12
+ 'For folders, requires a grant with "delete" in allowedOperations for the folder path. ' +
13
+ 'This operation cannot be undone — the item is not moved to the recycle bin. ' +
14
+ 'Call check_sharepoint_access first to verify permissions.', DeleteDriveItemSchema.shape, async (params) => {
15
+ try {
16
+ const library = resolveSharepointLibrary(config, params.libraryId);
17
+ logger.info('delete_drive_item', { libraryId: library.id, path: params.path });
18
+ const token = await auth.getAccessToken(config.accounts[0].id);
19
+ const client = createGraphClient(token);
20
+ // Pre-flight GET to determine whether the target is a file or folder.
21
+ // This drives guard selection: files need assertFileAccess (all 3 axes);
22
+ // folders need assertFolderAccess (path + operation only).
23
+ const item = (await getDriveItem(client, library.driveId, params.path));
24
+ if (item.folder !== undefined) {
25
+ // Folder: check path + operation only
26
+ assertFolderAccess(library, params.path, 'delete');
27
+ }
28
+ else {
29
+ // File (or unknown): check path + filename + operation
30
+ const { folderPath, filename } = splitPath(params.path);
31
+ assertFileAccess(library, folderPath, filename, 'delete');
32
+ }
33
+ await deleteDriveItem(client, library.driveId, params.path);
34
+ return {
35
+ content: [
36
+ {
37
+ type: 'text',
38
+ text: JSON.stringify({ deleted: true, path: params.path }, null, 2),
39
+ },
40
+ ],
41
+ };
42
+ }
43
+ catch (err) {
44
+ logger.error('delete_drive_item failed', { libraryId: params.libraryId });
45
+ return errorResponse(err);
46
+ }
47
+ });
48
+ }
@@ -0,0 +1,63 @@
1
+ import { DownloadFileSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { downloadFile } from '../../graph/sharepoint.js';
4
+ import { assertFileAccess } from '../../middleware/sharepointGuard.js';
5
+ import { errorResponse } from '../../utils/errors.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ import { resolveSharepointLibrary } from '../../utils/resolveSharepointLibrary.js';
8
+ import { splitPath } from '../../utils/pathUtils.js';
9
+ const IMAGE_MIME_TYPES = new Set([
10
+ 'image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/svg+xml',
11
+ ]);
12
+ function mimeFromExtension(filename) {
13
+ const ext = filename.split('.').pop()?.toLowerCase() ?? '';
14
+ const map = {
15
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',
16
+ gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml',
17
+ pdf: 'application/pdf',
18
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
19
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
20
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
21
+ txt: 'text/plain', csv: 'text/csv', json: 'application/json',
22
+ };
23
+ return map[ext] ?? 'application/octet-stream';
24
+ }
25
+ export function registerDownloadFile(server, config, auth) {
26
+ server.tool('download_file', 'Download a file from a SharePoint document library as base64-encoded content. ' +
27
+ 'Images are returned as MCP image content; all other files are returned as a JSON ' +
28
+ 'payload with fileName, mimeType, encoding ("base64"), and data. ' +
29
+ 'Maximum file size: 4 MB. ' +
30
+ 'Requires a grant with "read" in allowedOperations for the file\'s path and filename. ' +
31
+ 'Call check_sharepoint_access first to verify permissions.', DownloadFileSchema.shape, async (params) => {
32
+ try {
33
+ const library = resolveSharepointLibrary(config, params.libraryId);
34
+ const { folderPath, filename } = splitPath(params.path);
35
+ logger.info('download_file', { libraryId: library.id, path: params.path });
36
+ assertFileAccess(library, folderPath, filename, 'read');
37
+ const token = await auth.getAccessToken(config.accounts[0].id);
38
+ const client = createGraphClient(token);
39
+ const bytes = await downloadFile(client, library.driveId, params.path);
40
+ const mimeType = mimeFromExtension(filename);
41
+ const data = Buffer.from(bytes).toString('base64');
42
+ if (IMAGE_MIME_TYPES.has(mimeType)) {
43
+ return {
44
+ content: [
45
+ { type: 'image', data, mimeType: mimeType },
46
+ ],
47
+ };
48
+ }
49
+ return {
50
+ content: [
51
+ {
52
+ type: 'text',
53
+ text: JSON.stringify({ fileName: filename, mimeType, encoding: 'base64', data }, null, 2),
54
+ },
55
+ ],
56
+ };
57
+ }
58
+ catch (err) {
59
+ logger.error('download_file failed', { libraryId: params.libraryId });
60
+ return errorResponse(err);
61
+ }
62
+ });
63
+ }
@@ -0,0 +1,25 @@
1
+ import { GetDriveItemSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { getDriveItem } from '../../graph/sharepoint.js';
4
+ import { errorResponse } from '../../utils/errors.js';
5
+ import { logger } from '../../utils/logger.js';
6
+ import { resolveSharepointLibrary } from '../../utils/resolveSharepointLibrary.js';
7
+ export function registerGetDriveItem(server, config, auth) {
8
+ server.tool('get_drive_item', 'Get metadata for a specific file or folder in a SharePoint document library. ' +
9
+ 'Always permitted — no grant required. Returns full item metadata including id, name, ' +
10
+ 'size, type, dates, webUrl, and parentReference. ' +
11
+ 'To download the file content, use download_file (which requires a read grant).', GetDriveItemSchema.shape, async (params) => {
12
+ try {
13
+ const library = resolveSharepointLibrary(config, params.libraryId);
14
+ logger.info('get_drive_item', { libraryId: library.id, path: params.path });
15
+ const token = await auth.getAccessToken(config.accounts[0].id);
16
+ const client = createGraphClient(token);
17
+ const result = await getDriveItem(client, library.driveId, params.path);
18
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
19
+ }
20
+ catch (err) {
21
+ logger.error('get_drive_item failed', { libraryId: params.libraryId });
22
+ return errorResponse(err);
23
+ }
24
+ });
25
+ }
@@ -0,0 +1,25 @@
1
+ import { ListDriveItemsSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { listDriveItems } from '../../graph/sharepoint.js';
4
+ import { errorResponse } from '../../utils/errors.js';
5
+ import { logger } from '../../utils/logger.js';
6
+ import { resolveSharepointLibrary } from '../../utils/resolveSharepointLibrary.js';
7
+ export function registerListDriveItems(server, config, auth) {
8
+ server.tool('list_drive_items', 'List files and folders at a path in a SharePoint document library. ' +
9
+ 'Always permitted — no grant required. Returns name, size, type (file/folder), ' +
10
+ 'creation and modification dates, and webUrl for each item. ' +
11
+ 'Use check_sharepoint_access to verify whether you can download or modify a specific file.', ListDriveItemsSchema.shape, async (params) => {
12
+ try {
13
+ const library = resolveSharepointLibrary(config, params.libraryId);
14
+ logger.info('list_drive_items', { libraryId: library.id, path: params.path });
15
+ const token = await auth.getAccessToken(config.accounts[0].id);
16
+ const client = createGraphClient(token);
17
+ const result = await listDriveItems(client, library.driveId, params.path);
18
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
19
+ }
20
+ catch (err) {
21
+ logger.error('list_drive_items failed', { libraryId: params.libraryId });
22
+ return errorResponse(err);
23
+ }
24
+ });
25
+ }
@@ -0,0 +1,47 @@
1
+ import { ListSharepointLibrariesSchema } from '../schemas.js';
2
+ import { errorResponse } from '../../utils/errors.js';
3
+ import { logger } from '../../utils/logger.js';
4
+ export function registerListSharepointLibraries(server, config) {
5
+ server.tool('list_sharepoint_libraries', 'List all configured SharePoint document libraries. Returns library IDs, display names, ' +
6
+ 'grant configuration (allowedPaths, allowedFiles, allowedOperations per grant), and whether ' +
7
+ 'search is enabled. Use the returned libraryId with all other SharePoint tools. ' +
8
+ 'Directory listing (list_drive_items) and metadata (get_drive_item) are always permitted on ' +
9
+ 'any configured library — no grant required. File content operations require a matching grant.', ListSharepointLibrariesSchema.shape, async () => {
10
+ try {
11
+ logger.info('list_sharepoint_libraries');
12
+ if (!config.sharepoint || config.sharepoint.length === 0) {
13
+ return {
14
+ content: [
15
+ {
16
+ type: 'text',
17
+ text: JSON.stringify({ libraries: [], message: 'No SharePoint libraries are configured.' }, null, 2),
18
+ },
19
+ ],
20
+ };
21
+ }
22
+ const libraries = config.sharepoint.map((lib) => ({
23
+ id: lib.id,
24
+ displayName: lib.displayName,
25
+ searchAllowed: lib.searchAllowed,
26
+ globalAllowedOperations: lib.globalAllowedOperations,
27
+ globalAllowedFiles: lib.globalAllowedFiles,
28
+ grantCount: lib.grants.length,
29
+ grants: lib.grants.map((g, i) => ({
30
+ index: i,
31
+ ...(g.name !== undefined && { name: g.name }),
32
+ ...(g.description !== undefined && { description: g.description }),
33
+ allowedPaths: g.allowedPaths,
34
+ effectiveAllowedFiles: g.allowedFiles ?? lib.globalAllowedFiles,
35
+ effectiveAllowedOperations: g.allowedOperations ?? lib.globalAllowedOperations,
36
+ ...(g.allowedFiles !== undefined && { allowedFilesOverride: g.allowedFiles }),
37
+ ...(g.allowedOperations !== undefined && { allowedOperationsOverride: g.allowedOperations }),
38
+ })),
39
+ }));
40
+ return { content: [{ type: 'text', text: JSON.stringify({ libraries }, null, 2) }] };
41
+ }
42
+ catch (err) {
43
+ logger.error('list_sharepoint_libraries failed');
44
+ return errorResponse(err);
45
+ }
46
+ });
47
+ }
@@ -0,0 +1,48 @@
1
+ import { MoveDriveItemSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { getDriveItem, moveDriveItem } from '../../graph/sharepoint.js';
4
+ import { assertFileAccess, assertFolderAccess } from '../../middleware/sharepointGuard.js';
5
+ import { errorResponse } from '../../utils/errors.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ import { resolveSharepointLibrary } from '../../utils/resolveSharepointLibrary.js';
8
+ import { splitPath } from '../../utils/pathUtils.js';
9
+ export function registerMoveDriveItem(server, config, auth) {
10
+ server.tool('move_drive_item', 'Move a file or folder to a different location within a SharePoint document library, ' +
11
+ 'optionally renaming it at the same time. ' +
12
+ 'Requires a grant with "update" in allowedOperations for the source path/file, ' +
13
+ 'AND a grant with "create" in allowedOperations for the destination folder path. ' +
14
+ 'Both checks must pass before any Graph call is made. ' +
15
+ 'Call check_sharepoint_access first to verify permissions for both sides.', MoveDriveItemSchema.shape, async (params) => {
16
+ try {
17
+ const library = resolveSharepointLibrary(config, params.libraryId);
18
+ logger.info('move_drive_item', {
19
+ libraryId: library.id,
20
+ sourcePath: params.sourcePath,
21
+ destFolderPath: params.destFolderPath,
22
+ newName: params.newName,
23
+ });
24
+ const token = await auth.getAccessToken(config.accounts[0].id);
25
+ const client = createGraphClient(token);
26
+ // Pre-flight GET to determine whether the source is a file or folder.
27
+ // This drives guard selection for the source side of the move.
28
+ const sourceItem = (await getDriveItem(client, library.driveId, params.sourcePath));
29
+ if (sourceItem.folder !== undefined) {
30
+ // Source is a folder — check path + operation only (no file axis)
31
+ assertFolderAccess(library, params.sourcePath, 'update');
32
+ }
33
+ else {
34
+ // Source is a file — check all three axes
35
+ const { folderPath, filename } = splitPath(params.sourcePath);
36
+ assertFileAccess(library, folderPath, filename, 'update');
37
+ }
38
+ // Destination: always a folder — check path + operation only
39
+ assertFolderAccess(library, params.destFolderPath, 'create');
40
+ const result = await moveDriveItem(client, library.driveId, params.sourcePath, params.destFolderPath, params.newName);
41
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
42
+ }
43
+ catch (err) {
44
+ logger.error('move_drive_item failed', { libraryId: params.libraryId });
45
+ return errorResponse(err);
46
+ }
47
+ });
48
+ }
@@ -0,0 +1,79 @@
1
+ import { SearchDriveSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { searchDrive } from '../../graph/sharepoint.js';
4
+ import { evaluateFileAccess } from '../../middleware/sharepointGuard.js';
5
+ import { ToolError, errorResponse } from '../../utils/errors.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ import { resolveSharepointLibrary } from '../../utils/resolveSharepointLibrary.js';
8
+ import { normalisePath } from '../../utils/pathUtils.js';
9
+ /**
10
+ * Strip the Graph drive path prefix from a parentReference.path value.
11
+ *
12
+ * Graph returns paths like:
13
+ * /drives/{driveId}/root:/Finance/Reports → "/Finance/Reports"
14
+ * /drives/{driveId}/root: → "/"
15
+ * /drives/{driveId}/root → "/"
16
+ *
17
+ * We normalise the extracted path so grant evaluation is case-insensitive
18
+ * and consistent with how assertFileAccess / evaluateFileAccess normalise paths.
19
+ */
20
+ function extractFolderPath(parentReferencePath) {
21
+ if (!parentReferencePath)
22
+ return '/';
23
+ // Strip everything up to and including "root:" or "root"
24
+ const match = /root:?(\/.*)?$/.exec(parentReferencePath);
25
+ if (!match)
26
+ return '/';
27
+ const extracted = match[1] ?? '/';
28
+ return normalisePath(extracted || '/');
29
+ }
30
+ export function registerSearchDrive(server, config, auth) {
31
+ server.tool('search_drive', 'Search for files within a SharePoint document library using Microsoft Graph full-text search. ' +
32
+ 'Only available for libraries configured with searchAllowed: true. ' +
33
+ 'Results are filtered by the library grant configuration: ' +
34
+ 'only files where all three grant axes pass (allowedPaths, allowedFiles, allowedOperations) ' +
35
+ 'are returned. Everything else is silently dropped — no partial matches or hints are revealed. ' +
36
+ 'Use scopePath to limit the search to a specific folder subtree.', SearchDriveSchema.shape, async (params) => {
37
+ try {
38
+ const library = resolveSharepointLibrary(config, params.libraryId);
39
+ logger.info('search_drive', {
40
+ libraryId: library.id,
41
+ query: params.query,
42
+ scopePath: params.scopePath,
43
+ maxResults: params.maxResults,
44
+ });
45
+ if (!library.searchAllowed) {
46
+ throw new ToolError(`Search is not enabled for library "${library.id}". ` +
47
+ 'Set searchAllowed: true in the library config to enable search_drive.', 'SEARCH_NOT_ENABLED');
48
+ }
49
+ const token = await auth.getAccessToken(config.accounts[0].id);
50
+ const client = createGraphClient(token);
51
+ const items = await searchDrive(client, library.driveId, params.query, params.scopePath, params.maxResults);
52
+ // Client-side grant filtering
53
+ const results = [];
54
+ for (const item of items) {
55
+ // Skip folders — we only surface file results from search
56
+ if (item.folder !== undefined)
57
+ continue;
58
+ const folderPath = extractFolderPath(item.parentReference?.path);
59
+ const filename = item.name;
60
+ // All three axes must pass (path + file + operation) — anything that
61
+ // does not satisfy a full grant match is silently dropped with no hint.
62
+ const readResult = evaluateFileAccess(library, folderPath, filename, 'read');
63
+ if (readResult.allowed) {
64
+ results.push({
65
+ name: filename,
66
+ path: folderPath === '/' ? `/${filename}` : `${folderPath}/${filename}`,
67
+ ...(item.webUrl !== undefined && { webUrl: item.webUrl }),
68
+ ...(item.size !== undefined && { size: item.size }),
69
+ });
70
+ }
71
+ }
72
+ return { content: [{ type: 'text', text: JSON.stringify({ results }, null, 2) }] };
73
+ }
74
+ catch (err) {
75
+ logger.error('search_drive failed', { libraryId: params.libraryId });
76
+ return errorResponse(err);
77
+ }
78
+ });
79
+ }
@@ -0,0 +1,41 @@
1
+ import { UploadFileSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { uploadFile } from '../../graph/sharepoint.js';
4
+ import { evaluateFileAccess } from '../../middleware/sharepointGuard.js';
5
+ import { ToolError, errorResponse } from '../../utils/errors.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ import { resolveSharepointLibrary } from '../../utils/resolveSharepointLibrary.js';
8
+ import { splitPath } from '../../utils/pathUtils.js';
9
+ const MAX_BYTES = 4 * 1024 * 1024; // 4 MB
10
+ export function registerUploadFile(server, config, auth) {
11
+ server.tool('upload_file', 'Upload a file to a SharePoint document library. Accepts base64-encoded content. ' +
12
+ 'Creates the file if it does not exist; overwrites if it does. Maximum 4 MB. ' +
13
+ 'Requires a grant with "create" OR "update" in allowedOperations for the path and filename. ' +
14
+ 'Call check_sharepoint_access first to verify permissions.', UploadFileSchema.shape, async (params) => {
15
+ try {
16
+ const library = resolveSharepointLibrary(config, params.libraryId);
17
+ const { folderPath, filename } = splitPath(params.path);
18
+ logger.info('upload_file', { libraryId: library.id, path: params.path });
19
+ // upload_file requires "create" OR "update" — check both and allow if either passes
20
+ const createResult = evaluateFileAccess(library, folderPath, filename, 'create');
21
+ const updateResult = evaluateFileAccess(library, folderPath, filename, 'update');
22
+ if (!createResult.allowed && !updateResult.allowed) {
23
+ // Report whichever gives a more relevant message (create is the more common intent)
24
+ throw new ToolError(createResult.reason, 'ACCESS_DENIED');
25
+ }
26
+ const buf = Buffer.from(params.content, 'base64');
27
+ if (buf.byteLength > MAX_BYTES) {
28
+ throw new ToolError(`File is ${(buf.byteLength / 1024 / 1024).toFixed(1)} MB which exceeds the 4 MB ` +
29
+ 'simple upload limit. For larger files, chunked upload (resumable sessions) is required.', 'PAYLOAD_TOO_LARGE');
30
+ }
31
+ const token = await auth.getAccessToken(config.accounts[0].id);
32
+ const client = createGraphClient(token);
33
+ const result = await uploadFile(client, library.driveId, params.path, buf, params.contentType);
34
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
35
+ }
36
+ catch (err) {
37
+ logger.error('upload_file failed', { libraryId: params.libraryId });
38
+ return errorResponse(err);
39
+ }
40
+ });
41
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Path utilities for SharePoint drive operations.
3
+ *
4
+ * All path comparisons in the grant guard are case-insensitive and normalised
5
+ * through normalisePath() before matching.
6
+ */
7
+ /**
8
+ * Normalise a path for consistent comparison:
9
+ * - Lowercase
10
+ * - Ensure a leading slash
11
+ * - Strip trailing slash (except root "/")
12
+ *
13
+ * Examples:
14
+ * normalisePath("Finance/Reports/") → "/finance/reports"
15
+ * normalisePath("/") → "/"
16
+ * normalisePath("") → "/"
17
+ */
18
+ export function normalisePath(p) {
19
+ let n = p.trim().toLowerCase();
20
+ if (!n.startsWith('/'))
21
+ n = '/' + n;
22
+ if (n.length > 1 && n.endsWith('/'))
23
+ n = n.slice(0, -1);
24
+ return n || '/';
25
+ }
26
+ /**
27
+ * Split a full file path into its parent folder path and filename.
28
+ *
29
+ * Examples:
30
+ * splitPath("/Finance/Reports/Q1.pdf") → { folderPath: "/Finance/Reports", filename: "Q1.pdf" }
31
+ * splitPath("/Q1.pdf") → { folderPath: "/", filename: "Q1.pdf" }
32
+ * splitPath("Q1.pdf") → { folderPath: "/", filename: "Q1.pdf" }
33
+ */
34
+ export function splitPath(fullPath) {
35
+ const p = fullPath.trim();
36
+ const lastSlash = p.lastIndexOf('/');
37
+ if (lastSlash <= 0) {
38
+ return { folderPath: '/', filename: p.replace(/^\//, '') };
39
+ }
40
+ return {
41
+ folderPath: p.slice(0, lastSlash),
42
+ filename: p.slice(lastSlash + 1),
43
+ };
44
+ }
45
+ /**
46
+ * Build a Graph API drive path URL segment.
47
+ *
48
+ * Examples:
49
+ * buildDrivePath("id", "/") → "/drives/id/root"
50
+ * buildDrivePath("id", "/Finance") → "/drives/id/root:/Finance"
51
+ *
52
+ * Each path segment is URI-encoded individually so that folder names containing
53
+ * spaces or special characters are handled correctly.
54
+ */
55
+ export function buildDrivePath(driveId, path) {
56
+ const clean = path.trim().replace(/^\//, '').replace(/\/$/, '');
57
+ if (!clean)
58
+ return `/drives/${driveId}/root`;
59
+ const encoded = clean.split('/').map((seg) => encodeURIComponent(seg)).join('/');
60
+ return `/drives/${driveId}/root:/${encoded}`;
61
+ }
@@ -0,0 +1,19 @@
1
+ import { ToolError } from './errors.js';
2
+ /**
3
+ * Resolve a SharePoint library from the config by ID.
4
+ *
5
+ * Throws CONFIG_ERROR if:
6
+ * - config.sharepoint is not defined
7
+ * - the given libraryId is not found
8
+ */
9
+ export function resolveSharepointLibrary(config, libraryId) {
10
+ if (!config.sharepoint || config.sharepoint.length === 0) {
11
+ throw new ToolError('No SharePoint libraries are configured. Add a "sharepoint" section to your config file.', 'CONFIG_ERROR');
12
+ }
13
+ const library = config.sharepoint.find((lib) => lib.id === libraryId);
14
+ if (!library) {
15
+ const valid = config.sharepoint.map((lib) => `"${lib.id}"`).join(', ');
16
+ throw new ToolError(`Unknown SharePoint library ID: "${libraryId}". Configured libraries: ${valid}.`, 'CONFIG_ERROR');
17
+ }
18
+ return library;
19
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@teamnetwork-nz/m365-mcp-server",
3
- "version": "1.0.7",
4
- "description": "MCP server for Microsoft 365 Email and Calendar access using client credentials (app-only auth). Supports multiple accounts, shared mailboxes, per-mailbox read-only access, folder navigation, and date/content filtering.",
3
+ "version": "1.1.1",
4
+ "description": "MCP server for Microsoft 365 — Email, Calendar, To Do, and SharePoint document libraries — 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",
7
7
  "bin": {