@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.
@@ -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,94 @@
1
+ import { SearchDriveSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { searchDrive } from '../../graph/sharepoint.js';
4
+ import { evaluateFileAccess, pathIsConfigured } 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
+ 'files in paths and matching file patterns allowed by grants are returned in results[]; ' +
35
+ 'files in configured paths but restricted by file pattern or operation grants contribute to ' +
36
+ 'restrictedMatchCount (so you know relevant content exists but is inaccessible); ' +
37
+ 'files completely outside all configured allowedPaths are silently dropped. ' +
38
+ 'Use scopePath to limit the search to a specific folder subtree.', SearchDriveSchema.shape, async (params) => {
39
+ try {
40
+ const library = resolveSharepointLibrary(config, params.libraryId);
41
+ logger.info('search_drive', {
42
+ libraryId: library.id,
43
+ query: params.query,
44
+ scopePath: params.scopePath,
45
+ maxResults: params.maxResults,
46
+ });
47
+ if (!library.searchAllowed) {
48
+ throw new ToolError(`Search is not enabled for library "${library.id}". ` +
49
+ 'Set searchAllowed: true in the library config to enable search_drive.', 'SEARCH_NOT_ENABLED');
50
+ }
51
+ const token = await auth.getAccessToken(config.accounts[0].id);
52
+ const client = createGraphClient(token);
53
+ const items = await searchDrive(client, library.driveId, params.query, params.scopePath, params.maxResults);
54
+ // Client-side grant filtering
55
+ const results = [];
56
+ let restrictedMatchCount = 0;
57
+ for (const item of items) {
58
+ // Skip folders — we only surface file results from search
59
+ if (item.folder !== undefined)
60
+ continue;
61
+ const folderPath = extractFolderPath(item.parentReference?.path);
62
+ const filename = item.name;
63
+ // Check full read access (path + file + operation)
64
+ const readResult = evaluateFileAccess(library, folderPath, filename, 'read');
65
+ if (readResult.allowed) {
66
+ results.push({
67
+ name: filename,
68
+ path: folderPath === '/' ? `/${filename}` : `${folderPath}/${filename}`,
69
+ ...(item.webUrl !== undefined && { webUrl: item.webUrl }),
70
+ ...(item.size !== undefined && { size: item.size }),
71
+ });
72
+ }
73
+ else if (pathIsConfigured(library, folderPath)) {
74
+ // Path is within a configured grant's scope, but file or operation
75
+ // is restricted — count it without revealing what the file is.
76
+ restrictedMatchCount++;
77
+ }
78
+ // else: path is outside all configured allowedPaths — silently drop
79
+ }
80
+ const response = { results };
81
+ if (restrictedMatchCount > 0) {
82
+ response['restrictedMatchCount'] = restrictedMatchCount;
83
+ response['restrictedMatchNote'] =
84
+ `${restrictedMatchCount} additional matching file${restrictedMatchCount === 1 ? '' : 's'} ` +
85
+ 'were found in accessible folders but are not accessible with current permissions.';
86
+ }
87
+ return { content: [{ type: 'text', text: JSON.stringify(response, null, 2) }] };
88
+ }
89
+ catch (err) {
90
+ logger.error('search_drive failed', { libraryId: params.libraryId });
91
+ return errorResponse(err);
92
+ }
93
+ });
94
+ }
@@ -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
+ }