@teamnetwork-nz/m365-mcp-server 1.1.0 → 1.2.2

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
@@ -219,6 +219,7 @@ Operations always target exactly one mailbox per request, either the default or
219
219
 
220
220
  | Tool | Description |
221
221
  |---|---|
222
+ | `discover_sharepoint_sites` | Search for SharePoint sites and their document library drives — returns the `siteId`/`driveId` values needed to add a library to config. Always available, no `sharepoint` config required |
222
223
  | `list_sharepoint_libraries` | List configured SharePoint libraries with their grant definitions |
223
224
  | `list_drive_items` | List files and folders at a path — always permitted, no grant required |
224
225
  | `get_drive_item` | Get metadata for a file or folder — always permitted, no grant required |
@@ -228,7 +229,7 @@ Operations always target exactly one mailbox per request, either the default or
228
229
  | `create_folder` | Create a new folder. Requires `create` grant on the parent path |
229
230
  | `delete_drive_item` | Permanently delete a file or folder. Requires `delete` grant |
230
231
  | `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
+ | `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
 
233
234
  #### SharePoint grant model
234
235
 
@@ -272,17 +273,63 @@ Access to file content and write operations is controlled by **grants** defined
272
273
  ]
273
274
  ```
274
275
 
276
+ ### Teams
277
+
278
+ | Tool | Description |
279
+ |---|---|
280
+ | `list_teams` | List teams in the tenant (filtered to the configured `allowedTeams` scope) |
281
+ | `list_channels` | List channels of a team |
282
+ | `list_team_members` | List team members with roles |
283
+ | `list_call_records` | List call records — participants, timing, modalities (metadata only, no content). Requires `callRecordsAllowed: true` |
284
+ | `get_call_record` | Get a single call record, optionally with per-session network/quality detail |
285
+ | `list_channel_messages` | List recent channel messages. Requires `channelMessagesAllowed: true` **and Microsoft protected-API approval** |
286
+ | `get_channel_message` | Get a channel message, optionally with its reply thread. Same requirements |
287
+ | `list_chats` | List a configured user's chats. Requires `chatMessagesAllowed: true` **and Microsoft protected-API approval** |
288
+ | `list_chat_messages` | List messages in a chat. Same requirements; app-only chat reads may be metered by Microsoft |
289
+
290
+ #### Teams configuration
291
+
292
+ ```json
293
+ "teams": {
294
+ "allowedTeams": ["*"],
295
+ "callRecordsAllowed": true,
296
+ "channelMessagesAllowed": false,
297
+ "chatMessagesAllowed": false
298
+ }
299
+ ```
300
+
301
+ - Omit the `teams` block entirely to disable all Teams tools.
302
+ - `allowedTeams` gates every team-scoped call: `[]` = none, `["*"]` = all teams, or an explicit list of team IDs. `list_teams` silently omits teams outside the scope.
303
+ - Message tools are only registered when their flag is `true`.
304
+ - Chat access is restricted to mailboxes present in the config — other users in the tenant cannot be queried.
305
+
306
+ #### ⚠️ Protected APIs — message content requires Microsoft approval
307
+
308
+ Reading channel or chat **message content** with application permissions uses Microsoft Graph **protected APIs**. Admin consent in the Azure portal is *not sufficient* — you must also apply to Microsoft:
309
+
310
+ 1. Submit the [Microsoft Graph protected APIs request form](https://aka.ms/teamsgraph/requestaccess) with your app ID, publisher details, and data-use justification.
311
+ 2. Wait for approval (typically 1–3 weeks).
312
+ 3. Until approved, `list_channel_messages`, `get_channel_message`, `list_chats`, and `list_chat_messages` return **403 Forbidden** from Graph even though the permissions appear consented.
313
+
314
+ Structure tools (`list_teams`, `list_channels`, `list_team_members`) and call records work with ordinary application permissions — no Microsoft approval needed.
315
+
275
316
  #### Finding your siteId and driveId
276
317
 
277
- You can find these values in the [Azure Portal](https://portal.azure.com) → SharePoint admin centre, or by making a Graph API call:
318
+ Use the `discover_sharepoint_sites` tool — it needs only `Sites.Read.All` and works with no `sharepoint` config present, so it can be called before you've added a single library:
319
+
320
+ ```
321
+ discover_sharepoint_sites { "search": "Finance" }
322
+ ```
323
+
324
+ Returns each matching site's `siteId` (format `hostname,site-guid,web-guid`) along with its document library drives (`driveId`, `name`). Use `"search": "*"` to list every site the app can see — large tenants may see results truncated, in which case narrow with a keyword instead.
325
+
326
+ If you'd rather do it manually, the same data is available via the Azure Portal SharePoint admin centre or a direct Graph call:
278
327
 
279
328
  ```
280
329
  GET https://graph.microsoft.com/v1.0/sites/{hostname}:/sites/{sitePath}
281
330
  GET https://graph.microsoft.com/v1.0/sites/{siteId}/drives
282
331
  ```
283
332
 
284
- The `siteId` has the format `hostname,site-guid,web-guid`. The `driveId` is the `id` field on the default document library drive.
285
-
286
333
  ---
287
334
 
288
335
  ## Admin Setup
@@ -309,6 +356,12 @@ Grant the following **Application permissions** (not Delegated) and click **Gran
309
356
  | `Tasks.ReadWrite.All` | Reading and writing To Do lists and tasks |
310
357
  | `Sites.Read.All` | Reading SharePoint sites, drives, and file metadata |
311
358
  | `Sites.ReadWrite.All` | Uploading files, creating folders, deleting, and moving items in SharePoint |
359
+ | `Team.ReadBasic.All` | Listing teams |
360
+ | `Channel.ReadBasic.All` | Listing channels |
361
+ | `TeamMember.Read.All` | Listing team members |
362
+ | `CallRecords.Read.All` | Reading call records (metadata only) |
363
+ | `ChannelMessage.Read.All` | Reading channel messages — **protected API, requires Microsoft approval** (see Teams section) |
364
+ | `Chat.Read.All` | Reading chats and chat messages — **protected API, requires Microsoft approval** (see Teams section) |
312
365
 
313
366
  ### 2. Restrict Mailbox Access (Recommended)
314
367
 
@@ -71,5 +71,11 @@
71
71
  }
72
72
  ]
73
73
  }
74
- ]
74
+ ],
75
+ "teams": {
76
+ "allowedTeams": ["*"],
77
+ "callRecordsAllowed": true,
78
+ "channelMessagesAllowed": false,
79
+ "chatMessagesAllowed": false
80
+ }
75
81
  }
@@ -45,9 +45,17 @@ export const SharepointLibraryConfigSchema = z.object({
45
45
  globalAllowedFiles: z.array(z.string()),
46
46
  grants: z.array(SharepointGrantSchema),
47
47
  });
48
+ // ── Teams ───────────────────────────────────────────────────────────────────
49
+ export const TeamsConfigSchema = z.object({
50
+ allowedTeams: z.array(z.string()),
51
+ callRecordsAllowed: z.boolean().default(false),
52
+ channelMessagesAllowed: z.boolean().default(false),
53
+ chatMessagesAllowed: z.boolean().default(false),
54
+ });
48
55
  // ── Root config ─────────────────────────────────────────────────────────────
49
56
  export const AppConfigSchema = z.object({
50
57
  connection: ConnectionConfigSchema,
51
58
  accounts: z.array(AccountConfigSchema).min(1, 'Config must have at least one account'),
52
59
  sharepoint: z.array(SharepointLibraryConfigSchema).optional(),
60
+ teams: TeamsConfigSchema.optional(),
53
61
  });
@@ -2,6 +2,40 @@ import { ResponseType } from '@microsoft/microsoft-graph-client';
2
2
  import { mapGraphError } from '../utils/errors.js';
3
3
  import { buildDrivePath } from '../utils/pathUtils.js';
4
4
  const ITEM_SELECT = 'id,name,file,folder,size,createdDateTime,lastModifiedDateTime,webUrl,parentReference';
5
+ /**
6
+ * Search for SharePoint sites the app can see. Used to discover `siteId`
7
+ * values for the sharepoint config block — Graph's site IDs are otherwise
8
+ * only visible via the admin centre or manual Graph Explorer calls.
9
+ */
10
+ export async function discoverSites(client, search) {
11
+ try {
12
+ // The /sites endpoint takes a plain "search" query param (KQL-ish, "*" allowed
13
+ // as a special case meaning "everything"), NOT the OData $search param that
14
+ // .search() builds — $search=* is rejected by Graph as invalid KQL syntax.
15
+ const result = (await client
16
+ .api('/sites')
17
+ .query({ search })
18
+ .select('id,displayName,webUrl')
19
+ .get());
20
+ return result.value ?? [];
21
+ }
22
+ catch (err) {
23
+ throw mapGraphError(err, 'discover_sharepoint_sites');
24
+ }
25
+ }
26
+ /** List the document library drives for a site — used to discover `driveId` values. */
27
+ export async function listSiteDrives(client, siteId) {
28
+ try {
29
+ const result = (await client
30
+ .api(`/sites/${siteId}/drives`)
31
+ .select('id,name,driveType,webUrl')
32
+ .get());
33
+ return result.value ?? [];
34
+ }
35
+ catch (err) {
36
+ throw mapGraphError(err, 'list_site_drives');
37
+ }
38
+ }
5
39
  // ── Directory / metadata ────────────────────────────────────────────────────
6
40
  export async function listDriveItems(client, driveId, path) {
7
41
  try {
@@ -0,0 +1,107 @@
1
+ import { mapGraphError } from '../utils/errors.js';
2
+ export async function listTeams(client) {
3
+ try {
4
+ const result = (await client
5
+ .api('/teams')
6
+ .select('id,displayName,description,visibility,isArchived')
7
+ .get());
8
+ return result.value ?? [];
9
+ }
10
+ catch (err) {
11
+ throw mapGraphError(err, 'list_teams');
12
+ }
13
+ }
14
+ export async function listChannels(client, teamId) {
15
+ try {
16
+ return await client
17
+ .api(`/teams/${teamId}/channels`)
18
+ .select('id,displayName,description,membershipType,webUrl,createdDateTime')
19
+ .get();
20
+ }
21
+ catch (err) {
22
+ throw mapGraphError(err, 'list_channels');
23
+ }
24
+ }
25
+ export async function listTeamMembers(client, teamId) {
26
+ try {
27
+ return await client.api(`/teams/${teamId}/members`).get();
28
+ }
29
+ catch (err) {
30
+ throw mapGraphError(err, 'list_team_members');
31
+ }
32
+ }
33
+ // ── Phase 1: call records ───────────────────────────────────────────────────
34
+ export async function listCallRecords(client, startDateTime, endDateTime, maxResults) {
35
+ try {
36
+ let request = client.api('/communications/callRecords').top(maxResults);
37
+ const filters = [];
38
+ if (startDateTime)
39
+ filters.push(`startDateTime ge ${startDateTime}`);
40
+ if (endDateTime)
41
+ filters.push(`startDateTime lt ${endDateTime}`);
42
+ if (filters.length > 0)
43
+ request = request.filter(filters.join(' and '));
44
+ return await request.get();
45
+ }
46
+ catch (err) {
47
+ throw mapGraphError(err, 'list_call_records');
48
+ }
49
+ }
50
+ export async function getCallRecord(client, callRecordId, expandSessions) {
51
+ try {
52
+ let request = client.api(`/communications/callRecords/${callRecordId}`);
53
+ if (expandSessions)
54
+ request = request.expand('sessions');
55
+ return await request.get();
56
+ }
57
+ catch (err) {
58
+ throw mapGraphError(err, 'get_call_record');
59
+ }
60
+ }
61
+ // ── Phase 2: message content (protected APIs) ──────────────────────────────
62
+ export async function listChannelMessages(client, teamId, channelId, maxResults) {
63
+ try {
64
+ return await client
65
+ .api(`/teams/${teamId}/channels/${channelId}/messages`)
66
+ .top(maxResults)
67
+ .get();
68
+ }
69
+ catch (err) {
70
+ throw mapGraphError(err, 'list_channel_messages');
71
+ }
72
+ }
73
+ export async function getChannelMessage(client, teamId, channelId, messageId, includeReplies) {
74
+ try {
75
+ const message = await client
76
+ .api(`/teams/${teamId}/channels/${channelId}/messages/${messageId}`)
77
+ .get();
78
+ if (!includeReplies)
79
+ return message;
80
+ const replies = (await client
81
+ .api(`/teams/${teamId}/channels/${channelId}/messages/${messageId}/replies`)
82
+ .get());
83
+ return { ...message, replies: replies.value ?? [] };
84
+ }
85
+ catch (err) {
86
+ throw mapGraphError(err, 'get_channel_message');
87
+ }
88
+ }
89
+ export async function listChats(client, userEmail) {
90
+ try {
91
+ return await client
92
+ .api(`/users/${userEmail}/chats`)
93
+ .select('id,topic,chatType,createdDateTime,lastUpdatedDateTime,webUrl')
94
+ .get();
95
+ }
96
+ catch (err) {
97
+ throw mapGraphError(err, 'list_chats');
98
+ }
99
+ }
100
+ export async function listChatMessages(client, chatId, maxResults) {
101
+ try {
102
+ return await client.api(`/chats/${chatId}/messages`).top(maxResults).get();
103
+ }
104
+ catch (err) {
105
+ throw mapGraphError(err, 'list_chat_messages');
106
+ }
107
+ }
@@ -181,17 +181,6 @@ export function evaluateFolderAccess(library, folderPath, operation) {
181
181
  `folder "${folderPath}". Use check_sharepoint_access to inspect the grant configuration.`,
182
182
  };
183
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
184
  // ── Asserting guards (throw on deny) ────────────────────────────────────────
196
185
  /** Throws ToolError('ACCESS_DENIED') if file access is not permitted. */
197
186
  export function assertFileAccess(library, folderPath, filename, operation) {
@@ -0,0 +1,42 @@
1
+ import { ToolError } from '../utils/errors.js';
2
+ /**
3
+ * Teams access guard.
4
+ *
5
+ * - The `teams` config block must be present for any Teams tool to be registered.
6
+ * - allowedTeams gates every team-scoped call: [] = nothing, ["*"] = all teams,
7
+ * otherwise an explicit allowlist of team IDs.
8
+ * - Chat access is user-scoped and only permitted for mailboxes configured
9
+ * under accounts[].mailboxes.
10
+ */
11
+ /** Returns the teams config or throws CONFIG_ERROR when the block is absent. */
12
+ export function resolveTeamsConfig(config) {
13
+ if (!config.teams) {
14
+ throw new ToolError('Teams access is not configured. Add a "teams" block to the config file to enable Teams tools.', 'CONFIG_ERROR');
15
+ }
16
+ return config.teams;
17
+ }
18
+ /** Pure check: is this team ID within the allowedTeams scope? */
19
+ export function teamIsAllowed(teams, teamId) {
20
+ if (teams.allowedTeams.length === 0)
21
+ return false;
22
+ if (teams.allowedTeams.includes('*'))
23
+ return true;
24
+ return teams.allowedTeams.some((t) => t.toLowerCase() === teamId.toLowerCase());
25
+ }
26
+ /** Throws ToolError('ACCESS_DENIED') if the team is not in allowedTeams. */
27
+ export function assertTeamAllowed(teams, teamId) {
28
+ if (!teamIsAllowed(teams, teamId)) {
29
+ throw new ToolError(`Team "${teamId}" is not in the configured allowedTeams list.`, 'ACCESS_DENIED');
30
+ }
31
+ }
32
+ /**
33
+ * Throws ToolError('ACCESS_DENIED') unless the email belongs to a mailbox
34
+ * configured in the config file. Used to scope chat access to known users.
35
+ */
36
+ export function assertUserConfigured(config, email) {
37
+ const known = config.accounts.some((account) => account.mailboxes.some((mb) => mb.email.toLowerCase() === email.toLowerCase()));
38
+ if (!known) {
39
+ throw new ToolError(`Chat access is only permitted for mailboxes configured in the config file. ` +
40
+ `"${email}" is not a configured mailbox.`, 'ACCESS_DENIED');
41
+ }
42
+ }
@@ -37,6 +37,17 @@ import { registerCreateFolder } from './sharepoint/createFolder.js';
37
37
  import { registerDeleteDriveItem } from './sharepoint/deleteDriveItem.js';
38
38
  import { registerMoveDriveItem } from './sharepoint/moveDriveItem.js';
39
39
  import { registerSearchDrive } from './sharepoint/searchDrive.js';
40
+ import { registerDiscoverSharepointSites } from './sharepoint/discoverSharepointSites.js';
41
+ // Teams tools
42
+ import { registerListTeams } from './teams/listTeams.js';
43
+ import { registerListChannels } from './teams/listChannels.js';
44
+ import { registerListTeamMembers } from './teams/listTeamMembers.js';
45
+ import { registerListCallRecords } from './teams/listCallRecords.js';
46
+ import { registerGetCallRecord } from './teams/getCallRecord.js';
47
+ import { registerListChannelMessages } from './teams/listChannelMessages.js';
48
+ import { registerGetChannelMessage } from './teams/getChannelMessage.js';
49
+ import { registerListChats } from './teams/listChats.js';
50
+ import { registerListChatMessages } from './teams/listChatMessages.js';
40
51
  function registerEmailTools(server, config, auth) {
41
52
  registerListMailboxes(server, config);
42
53
  registerListFolders(server, config, auth);
@@ -69,6 +80,9 @@ function registerTodoTools(server, config, auth) {
69
80
  registerDeleteLinkedResource(server, config, auth);
70
81
  }
71
82
  function registerSharepointTools(server, config, auth) {
83
+ // discover_sharepoint_sites helps build the sharepoint config block, so it is
84
+ // registered unconditionally — it needs only Sites.Read.All, not a configured library.
85
+ registerDiscoverSharepointSites(server, config, auth);
72
86
  if (!config.sharepoint || config.sharepoint.length === 0)
73
87
  return;
74
88
  registerListSharepointLibraries(server, config);
@@ -88,10 +102,33 @@ function registerSharepointTools(server, config, auth) {
88
102
  registerSearchDrive(server, config, auth);
89
103
  }
90
104
  }
105
+ function registerTeamsTools(server, config, auth) {
106
+ if (!config.teams)
107
+ return;
108
+ // Phase 1 — structure. Ordinary application permissions.
109
+ registerListTeams(server, config, auth);
110
+ registerListChannels(server, config, auth);
111
+ registerListTeamMembers(server, config, auth);
112
+ // Phase 1 — call records. Gated by callRecordsAllowed.
113
+ if (config.teams.callRecordsAllowed) {
114
+ registerListCallRecords(server, config, auth);
115
+ registerGetCallRecord(server, config, auth);
116
+ }
117
+ // Phase 2 — message content. Gated by config flags AND Microsoft protected-API
118
+ // approval (Graph returns 403 until the app registration is approved).
119
+ if (config.teams.channelMessagesAllowed) {
120
+ registerListChannelMessages(server, config, auth);
121
+ registerGetChannelMessage(server, config, auth);
122
+ }
123
+ if (config.teams.chatMessagesAllowed) {
124
+ registerListChats(server, config, auth);
125
+ registerListChatMessages(server, config, auth);
126
+ }
127
+ }
91
128
  export function registerAllTools(server, config, auth) {
92
129
  registerEmailTools(server, config, auth);
93
130
  registerCalendarTools(server, config, auth);
94
131
  registerTodoTools(server, config, auth);
95
132
  registerSharepointTools(server, config, auth);
96
- // Future: registerTeamsTools(server, config, auth);
133
+ registerTeamsTools(server, config, auth);
97
134
  }
@@ -242,3 +242,72 @@ export const UpdateLinkedResourceSchema = TaskBase.extend({
242
242
  export const DeleteLinkedResourceSchema = TaskBase.extend({
243
243
  linkedResourceId: z.string().describe('The linked resource ID to delete'),
244
244
  });
245
+ // ── Teams tools ────────────────────────────────────────────────────────────
246
+ //
247
+ // Access model:
248
+ // - The "teams" config block must be present for any Teams tool to register.
249
+ // - allowedTeams gates every team-scoped call: [] = none, ["*"] = all,
250
+ // or an explicit list of team IDs.
251
+ // - Call record tools require callRecordsAllowed: true.
252
+ // - Message tools require channelMessagesAllowed / chatMessagesAllowed: true
253
+ // AND Microsoft protected-API approval for the app registration
254
+ // (ChannelMessage.Read.All / Chat.Read.All return 403 until approved).
255
+ const TeamBase = z.object({
256
+ teamId: z.string().describe('The team ID (GUID). Use list_teams to discover team IDs.'),
257
+ });
258
+ export const ListTeamsSchema = z.object({});
259
+ export const ListChannelsSchema = TeamBase;
260
+ export const ListTeamMembersSchema = TeamBase;
261
+ export const ListCallRecordsSchema = z.object({
262
+ startDate: z
263
+ .string()
264
+ .optional()
265
+ .describe('Only include calls starting on/after this datetime (ISO 8601, local time accepted).'),
266
+ endDate: z
267
+ .string()
268
+ .optional()
269
+ .describe('Only include calls starting before this datetime (ISO 8601, local time accepted).'),
270
+ maxResults: z.number().int().min(1).max(100).default(25),
271
+ });
272
+ export const GetCallRecordSchema = z.object({
273
+ callRecordId: z.string().describe('The call record ID (GUID).'),
274
+ expandSessions: z
275
+ .boolean()
276
+ .default(false)
277
+ .describe('Include per-session detail (segments, endpoints, network quality).'),
278
+ });
279
+ export const ListChannelMessagesSchema = TeamBase.extend({
280
+ channelId: z.string().describe('The channel ID. Use list_channels to discover channel IDs.'),
281
+ maxResults: z.number().int().min(1).max(50).default(20),
282
+ });
283
+ export const GetChannelMessageSchema = TeamBase.extend({
284
+ channelId: z.string().describe('The channel ID.'),
285
+ messageId: z.string().describe('The message ID.'),
286
+ includeReplies: z.boolean().default(false).describe('Also fetch the reply thread for this message.'),
287
+ });
288
+ export const ListChatsSchema = z.object({
289
+ mailbox: z
290
+ .string()
291
+ .optional()
292
+ .describe('Email address of the user whose chats to list. Must be a configured mailbox. Defaults to the first configured mailbox.'),
293
+ });
294
+ export const ListChatMessagesSchema = z.object({
295
+ chatId: z.string().describe('The chat ID. Use list_chats to discover chat IDs.'),
296
+ maxResults: z.number().int().min(1).max(50).default(20),
297
+ });
298
+ // ── SharePoint discovery tool ────────────────────────────────────────────────
299
+ //
300
+ // Bootstraps the sharepoint config block by finding siteId and driveId values.
301
+ // Not gated by the "sharepoint" config section — it exists to help build it.
302
+ export const DiscoverSharepointSitesSchema = z.object({
303
+ search: z
304
+ .string()
305
+ .default('*')
306
+ .describe('Keyword to search for sites by name (e.g. "Finance", "HR"). ' +
307
+ 'Use "*" to list all sites visible to the app — may be truncated in large tenants, ' +
308
+ 'in which case narrow with a keyword instead.'),
309
+ includeDrives: z
310
+ .boolean()
311
+ .default(true)
312
+ .describe('Also fetch each matched site\'s document library drives (id, name). Adds one Graph call per site.'),
313
+ });
@@ -0,0 +1,53 @@
1
+ import { DiscoverSharepointSitesSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { discoverSites, listSiteDrives } from '../../graph/sharepoint.js';
4
+ import { errorResponse } from '../../utils/errors.js';
5
+ import { logger } from '../../utils/logger.js';
6
+ export function registerDiscoverSharepointSites(server, config, auth) {
7
+ server.tool('discover_sharepoint_sites', 'Search for SharePoint sites and their document library drives — use this to find the ' +
8
+ '"siteId" and "driveId" values needed to add a library to the sharepoint config block. ' +
9
+ 'Always available regardless of current sharepoint config — this tool exists to help ' +
10
+ 'build that config, not to access its content. ' +
11
+ 'Requires only Sites.Read.All (no protected-API approval needed). ' +
12
+ 'Pass a keyword in "search" to narrow results, or "*" to list everything visible to the app. ' +
13
+ 'Some sites (hidden system sites, personal OneDrive-backed sites) reject drive listing even ' +
14
+ 'when the site itself is visible — those entries include a "drivesError" field instead of "drives".', DiscoverSharepointSitesSchema.shape, async (params) => {
15
+ try {
16
+ logger.info('discover_sharepoint_sites', { search: params.search, includeDrives: params.includeDrives });
17
+ const token = await auth.getAccessToken(config.accounts[0].id);
18
+ const client = createGraphClient(token);
19
+ const sites = await discoverSites(client, params.search);
20
+ const results = [];
21
+ for (const site of sites) {
22
+ const entry = {
23
+ siteId: site.id,
24
+ ...(site.displayName !== undefined && { displayName: site.displayName }),
25
+ ...(site.webUrl !== undefined && { webUrl: site.webUrl }),
26
+ };
27
+ if (params.includeDrives) {
28
+ // Some sites (hidden system sites, personal OneDrive-backed sites, etc.)
29
+ // reject drive listing even when the site itself is visible. Degrade
30
+ // gracefully per-site rather than aborting the whole discovery call.
31
+ try {
32
+ const drives = await listSiteDrives(client, site.id);
33
+ entry.drives = drives.map((d) => ({
34
+ driveId: d.id,
35
+ ...(d.name !== undefined && { name: d.name }),
36
+ ...(d.driveType !== undefined && { driveType: d.driveType }),
37
+ ...(d.webUrl !== undefined && { webUrl: d.webUrl }),
38
+ }));
39
+ }
40
+ catch (driveErr) {
41
+ entry.drivesError = driveErr instanceof Error ? driveErr.message : 'Failed to list drives';
42
+ }
43
+ }
44
+ results.push(entry);
45
+ }
46
+ return { content: [{ type: 'text', text: JSON.stringify({ sites: results }, null, 2) }] };
47
+ }
48
+ catch (err) {
49
+ logger.error('discover_sharepoint_sites failed', { search: params.search });
50
+ return errorResponse(err);
51
+ }
52
+ });
53
+ }
@@ -1,7 +1,7 @@
1
1
  import { SearchDriveSchema } from '../schemas.js';
2
2
  import { createGraphClient } from '../../graph/clientFactory.js';
3
3
  import { searchDrive } from '../../graph/sharepoint.js';
4
- import { evaluateFileAccess, pathIsConfigured } from '../../middleware/sharepointGuard.js';
4
+ import { evaluateFileAccess } from '../../middleware/sharepointGuard.js';
5
5
  import { ToolError, errorResponse } from '../../utils/errors.js';
6
6
  import { logger } from '../../utils/logger.js';
7
7
  import { resolveSharepointLibrary } from '../../utils/resolveSharepointLibrary.js';
@@ -31,10 +31,8 @@ export function registerSearchDrive(server, config, auth) {
31
31
  server.tool('search_drive', 'Search for files within a SharePoint document library using Microsoft Graph full-text search. ' +
32
32
  'Only available for libraries configured with searchAllowed: true. ' +
33
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. ' +
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. ' +
38
36
  'Use scopePath to limit the search to a specific folder subtree.', SearchDriveSchema.shape, async (params) => {
39
37
  try {
40
38
  const library = resolveSharepointLibrary(config, params.libraryId);
@@ -53,14 +51,14 @@ export function registerSearchDrive(server, config, auth) {
53
51
  const items = await searchDrive(client, library.driveId, params.query, params.scopePath, params.maxResults);
54
52
  // Client-side grant filtering
55
53
  const results = [];
56
- let restrictedMatchCount = 0;
57
54
  for (const item of items) {
58
55
  // Skip folders — we only surface file results from search
59
56
  if (item.folder !== undefined)
60
57
  continue;
61
58
  const folderPath = extractFolderPath(item.parentReference?.path);
62
59
  const filename = item.name;
63
- // Check full read access (path + file + operation)
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.
64
62
  const readResult = evaluateFileAccess(library, folderPath, filename, 'read');
65
63
  if (readResult.allowed) {
66
64
  results.push({
@@ -70,21 +68,8 @@ export function registerSearchDrive(server, config, auth) {
70
68
  ...(item.size !== undefined && { size: item.size }),
71
69
  });
72
70
  }
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
71
  }
87
- return { content: [{ type: 'text', text: JSON.stringify(response, null, 2) }] };
72
+ return { content: [{ type: 'text', text: JSON.stringify({ results }, null, 2) }] };
88
73
  }
89
74
  catch (err) {
90
75
  logger.error('search_drive failed', { libraryId: params.libraryId });
@@ -0,0 +1,30 @@
1
+ import { GetCallRecordSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { getCallRecord } from '../../graph/teams.js';
4
+ import { resolveTeamsConfig } from '../../middleware/teamsGuard.js';
5
+ import { ToolError, errorResponse } from '../../utils/errors.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ import { localizeResponseDates } from '../../utils/datetime.js';
8
+ export function registerGetCallRecord(server, config, auth) {
9
+ server.tool('get_call_record', 'Get a single Teams call record by ID — participants, timing, modalities, and version. ' +
10
+ 'Set expandSessions: true for per-session detail including endpoints and network quality ' +
11
+ 'statistics. Requires callRecordsAllowed: true in the teams config.', GetCallRecordSchema.shape, async (params) => {
12
+ try {
13
+ const teams = resolveTeamsConfig(config);
14
+ if (!teams.callRecordsAllowed) {
15
+ throw new ToolError('Call record access is not enabled. Set callRecordsAllowed: true in the teams config.', 'ACCESS_DENIED');
16
+ }
17
+ logger.info('get_call_record', { callRecordId: params.callRecordId });
18
+ const token = await auth.getAccessToken(config.accounts[0].id);
19
+ const client = createGraphClient(token);
20
+ const result = await getCallRecord(client, params.callRecordId, params.expandSessions);
21
+ return {
22
+ content: [{ type: 'text', text: JSON.stringify(localizeResponseDates(result), null, 2) }],
23
+ };
24
+ }
25
+ catch (err) {
26
+ logger.error('get_call_record failed', { callRecordId: params.callRecordId });
27
+ return errorResponse(err);
28
+ }
29
+ });
30
+ }
@@ -0,0 +1,33 @@
1
+ import { GetChannelMessageSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { getChannelMessage } from '../../graph/teams.js';
4
+ import { resolveTeamsConfig, assertTeamAllowed } from '../../middleware/teamsGuard.js';
5
+ import { errorResponse } from '../../utils/errors.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ import { localizeResponseDates } from '../../utils/datetime.js';
8
+ export function registerGetChannelMessage(server, config, auth) {
9
+ server.tool('get_channel_message', 'Get a single Teams channel message by ID, optionally with its reply thread. ' +
10
+ 'The team must be within the configured allowedTeams scope. ' +
11
+ 'Uses the ChannelMessage.Read.All protected API — see list_channel_messages for the ' +
12
+ 'Microsoft approval requirement.', GetChannelMessageSchema.shape, async (params) => {
13
+ try {
14
+ const teams = resolveTeamsConfig(config);
15
+ assertTeamAllowed(teams, params.teamId);
16
+ logger.info('get_channel_message', {
17
+ teamId: params.teamId,
18
+ channelId: params.channelId,
19
+ messageId: params.messageId,
20
+ });
21
+ const token = await auth.getAccessToken(config.accounts[0].id);
22
+ const client = createGraphClient(token);
23
+ const result = await getChannelMessage(client, params.teamId, params.channelId, params.messageId, params.includeReplies);
24
+ return {
25
+ content: [{ type: 'text', text: JSON.stringify(localizeResponseDates(result), null, 2) }],
26
+ };
27
+ }
28
+ catch (err) {
29
+ logger.error('get_channel_message failed', { teamId: params.teamId });
30
+ return errorResponse(err);
31
+ }
32
+ });
33
+ }
@@ -0,0 +1,31 @@
1
+ import { ListCallRecordsSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { listCallRecords } from '../../graph/teams.js';
4
+ import { resolveTeamsConfig } from '../../middleware/teamsGuard.js';
5
+ import { ToolError, errorResponse } from '../../utils/errors.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ import { toUtcIso, localizeResponseDates } from '../../utils/datetime.js';
8
+ export function registerListCallRecords(server, config, auth) {
9
+ server.tool('list_call_records', 'List Teams call records (metadata only — participants, start/end times, call type, ' +
10
+ 'modalities). No call content or audio is available. Optionally filter by a start ' +
11
+ 'datetime range. Requires callRecordsAllowed: true in the teams config. ' +
12
+ 'Note: call records typically appear 30-60 minutes after a call ends.', ListCallRecordsSchema.shape, async (params) => {
13
+ try {
14
+ const teams = resolveTeamsConfig(config);
15
+ if (!teams.callRecordsAllowed) {
16
+ throw new ToolError('Call record access is not enabled. Set callRecordsAllowed: true in the teams config.', 'ACCESS_DENIED');
17
+ }
18
+ logger.info('list_call_records', { startDate: params.startDate, endDate: params.endDate });
19
+ const token = await auth.getAccessToken(config.accounts[0].id);
20
+ const client = createGraphClient(token);
21
+ const result = await listCallRecords(client, params.startDate ? toUtcIso(params.startDate) : undefined, params.endDate ? toUtcIso(params.endDate) : undefined, params.maxResults);
22
+ return {
23
+ content: [{ type: 'text', text: JSON.stringify(localizeResponseDates(result), null, 2) }],
24
+ };
25
+ }
26
+ catch (err) {
27
+ logger.error('list_call_records failed', {});
28
+ return errorResponse(err);
29
+ }
30
+ });
31
+ }
@@ -0,0 +1,30 @@
1
+ import { ListChannelMessagesSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { listChannelMessages } from '../../graph/teams.js';
4
+ import { resolveTeamsConfig, assertTeamAllowed } from '../../middleware/teamsGuard.js';
5
+ import { errorResponse } from '../../utils/errors.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ import { localizeResponseDates } from '../../utils/datetime.js';
8
+ export function registerListChannelMessages(server, config, auth) {
9
+ server.tool('list_channel_messages', 'List recent messages in a Teams channel. The team must be within the configured ' +
10
+ 'allowedTeams scope. ' +
11
+ 'NOTE: this uses the ChannelMessage.Read.All protected API — if Microsoft has not ' +
12
+ 'approved the app registration for protected API access, Graph returns 403 Forbidden ' +
13
+ 'even though the permission is consented. That is an approval issue, not a config issue.', ListChannelMessagesSchema.shape, async (params) => {
14
+ try {
15
+ const teams = resolveTeamsConfig(config);
16
+ assertTeamAllowed(teams, params.teamId);
17
+ logger.info('list_channel_messages', { teamId: params.teamId, channelId: params.channelId });
18
+ const token = await auth.getAccessToken(config.accounts[0].id);
19
+ const client = createGraphClient(token);
20
+ const result = await listChannelMessages(client, params.teamId, params.channelId, params.maxResults);
21
+ return {
22
+ content: [{ type: 'text', text: JSON.stringify(localizeResponseDates(result), null, 2) }],
23
+ };
24
+ }
25
+ catch (err) {
26
+ logger.error('list_channel_messages failed', { teamId: params.teamId });
27
+ return errorResponse(err);
28
+ }
29
+ });
30
+ }
@@ -0,0 +1,24 @@
1
+ import { ListChannelsSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { listChannels } from '../../graph/teams.js';
4
+ import { resolveTeamsConfig, assertTeamAllowed } from '../../middleware/teamsGuard.js';
5
+ import { errorResponse } from '../../utils/errors.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ export function registerListChannels(server, config, auth) {
8
+ server.tool('list_channels', 'List the channels of a Microsoft Team. The team must be within the configured ' +
9
+ 'allowedTeams scope. Returns id, displayName, description, membershipType, and webUrl.', ListChannelsSchema.shape, async (params) => {
10
+ try {
11
+ const teams = resolveTeamsConfig(config);
12
+ assertTeamAllowed(teams, params.teamId);
13
+ logger.info('list_channels', { teamId: params.teamId });
14
+ const token = await auth.getAccessToken(config.accounts[0].id);
15
+ const client = createGraphClient(token);
16
+ const result = await listChannels(client, params.teamId);
17
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
18
+ }
19
+ catch (err) {
20
+ logger.error('list_channels failed', { teamId: params.teamId });
21
+ return errorResponse(err);
22
+ }
23
+ });
24
+ }
@@ -0,0 +1,29 @@
1
+ import { ListChatMessagesSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { listChatMessages } from '../../graph/teams.js';
4
+ import { resolveTeamsConfig } from '../../middleware/teamsGuard.js';
5
+ import { errorResponse } from '../../utils/errors.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ import { localizeResponseDates } from '../../utils/datetime.js';
8
+ export function registerListChatMessages(server, config, auth) {
9
+ server.tool('list_chat_messages', 'List recent messages in a specific chat. Use list_chats first to discover chat IDs — ' +
10
+ 'chat IDs can only be obtained for configured mailboxes, which scopes what is reachable. ' +
11
+ 'Uses the Chat.Read.All protected API — see list_chats for the Microsoft approval ' +
12
+ 'requirement. App-only chat message reads may also be metered (billed per message) ' +
13
+ 'beyond the free evaluation quota.', ListChatMessagesSchema.shape, async (params) => {
14
+ try {
15
+ resolveTeamsConfig(config);
16
+ logger.info('list_chat_messages', { chatId: params.chatId });
17
+ const token = await auth.getAccessToken(config.accounts[0].id);
18
+ const client = createGraphClient(token);
19
+ const result = await listChatMessages(client, params.chatId, params.maxResults);
20
+ return {
21
+ content: [{ type: 'text', text: JSON.stringify(localizeResponseDates(result), null, 2) }],
22
+ };
23
+ }
24
+ catch (err) {
25
+ logger.error('list_chat_messages failed', { chatId: params.chatId });
26
+ return errorResponse(err);
27
+ }
28
+ });
29
+ }
@@ -0,0 +1,31 @@
1
+ import { ListChatsSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { listChats } from '../../graph/teams.js';
4
+ import { resolveTeamsConfig, assertUserConfigured } from '../../middleware/teamsGuard.js';
5
+ import { errorResponse } from '../../utils/errors.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ import { localizeResponseDates } from '../../utils/datetime.js';
8
+ export function registerListChats(server, config, auth) {
9
+ server.tool('list_chats', 'List the 1:1 and group chats of a configured user. Chat access is restricted to ' +
10
+ 'mailboxes present in the config file — other users in the tenant cannot be queried. ' +
11
+ 'Uses the Chat.Read.All protected API — if Microsoft has not approved the app ' +
12
+ 'registration for protected API access, Graph returns 403 Forbidden even though the ' +
13
+ 'permission is consented.', ListChatsSchema.shape, async (params) => {
14
+ try {
15
+ resolveTeamsConfig(config);
16
+ const email = params.mailbox ?? config.accounts[0].mailboxes[0].email;
17
+ assertUserConfigured(config, email);
18
+ logger.info('list_chats', { mailbox: email });
19
+ const token = await auth.getAccessToken(config.accounts[0].id);
20
+ const client = createGraphClient(token);
21
+ const result = await listChats(client, email);
22
+ return {
23
+ content: [{ type: 'text', text: JSON.stringify(localizeResponseDates(result), null, 2) }],
24
+ };
25
+ }
26
+ catch (err) {
27
+ logger.error('list_chats failed', {});
28
+ return errorResponse(err);
29
+ }
30
+ });
31
+ }
@@ -0,0 +1,24 @@
1
+ import { ListTeamMembersSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { listTeamMembers } from '../../graph/teams.js';
4
+ import { resolveTeamsConfig, assertTeamAllowed } from '../../middleware/teamsGuard.js';
5
+ import { errorResponse } from '../../utils/errors.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ export function registerListTeamMembers(server, config, auth) {
8
+ server.tool('list_team_members', 'List the members of a Microsoft Team with their roles. The team must be within ' +
9
+ 'the configured allowedTeams scope.', ListTeamMembersSchema.shape, async (params) => {
10
+ try {
11
+ const teams = resolveTeamsConfig(config);
12
+ assertTeamAllowed(teams, params.teamId);
13
+ logger.info('list_team_members', { teamId: params.teamId });
14
+ const token = await auth.getAccessToken(config.accounts[0].id);
15
+ const client = createGraphClient(token);
16
+ const result = await listTeamMembers(client, params.teamId);
17
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
18
+ }
19
+ catch (err) {
20
+ logger.error('list_team_members failed', { teamId: params.teamId });
21
+ return errorResponse(err);
22
+ }
23
+ });
24
+ }
@@ -0,0 +1,25 @@
1
+ import { ListTeamsSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { listTeams } from '../../graph/teams.js';
4
+ import { resolveTeamsConfig, teamIsAllowed } from '../../middleware/teamsGuard.js';
5
+ import { errorResponse } from '../../utils/errors.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ export function registerListTeams(server, config, auth) {
8
+ server.tool('list_teams', 'List Microsoft Teams in the tenant. Only teams within the configured allowedTeams ' +
9
+ 'scope are returned — teams outside that scope are silently omitted. ' +
10
+ 'Returns id, displayName, description, visibility, and isArchived for each team.', ListTeamsSchema.shape, async () => {
11
+ try {
12
+ const teams = resolveTeamsConfig(config);
13
+ logger.info('list_teams', {});
14
+ const token = await auth.getAccessToken(config.accounts[0].id);
15
+ const client = createGraphClient(token);
16
+ const all = await listTeams(client);
17
+ const visible = all.filter((t) => teamIsAllowed(teams, t.id));
18
+ return { content: [{ type: 'text', text: JSON.stringify({ teams: visible }, null, 2) }] };
19
+ }
20
+ catch (err) {
21
+ logger.error('list_teams failed', {});
22
+ return errorResponse(err);
23
+ }
24
+ });
25
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@teamnetwork-nz/m365-mcp-server",
3
- "version": "1.1.0",
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.",
3
+ "version": "1.2.2",
4
+ "description": "MCP server for Microsoft 365 — Email, Calendar, To Do, SharePoint document libraries, and Teams — using client credentials (app-only auth). Supports multiple accounts, shared mailboxes, per-mailbox read-only access, and grant-based SharePoint access control.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "bin": {