@teamnetwork-nz/m365-mcp-server 1.0.5
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 +264 -0
- package/config.example.json +27 -0
- package/dist/auth/AuthManager.js +19 -0
- package/dist/auth/TokenCache.js +25 -0
- package/dist/config/loader.js +31 -0
- package/dist/config/schema.js +23 -0
- package/dist/config/types.js +1 -0
- package/dist/graph/attachments.js +71 -0
- package/dist/graph/calendar.js +109 -0
- package/dist/graph/clientFactory.js +8 -0
- package/dist/graph/email.js +138 -0
- package/dist/index.js +30 -0
- package/dist/middleware/readonlyGuard.js +29 -0
- package/dist/tools/calendar/createEvent.js +38 -0
- package/dist/tools/calendar/getEvent.js +25 -0
- package/dist/tools/calendar/listCalendars.js +24 -0
- package/dist/tools/calendar/listEvents.js +42 -0
- package/dist/tools/calendar/updateEvent.js +40 -0
- package/dist/tools/email/downloadAttachment.js +43 -0
- package/dist/tools/email/getMessage.js +25 -0
- package/dist/tools/email/listFolders.js +26 -0
- package/dist/tools/email/listMailboxes.js +30 -0
- package/dist/tools/email/listMessageAttachments.js +26 -0
- package/dist/tools/email/listMessages.js +50 -0
- package/dist/tools/email/moveMessage.js +26 -0
- package/dist/tools/email/replyMessage.js +28 -0
- package/dist/tools/email/sendMessage.js +32 -0
- package/dist/tools/registry.js +39 -0
- package/dist/tools/schemas.js +91 -0
- package/dist/utils/datetime.js +162 -0
- package/dist/utils/errors.js +48 -0
- package/dist/utils/logger.js +32 -0
- package/dist/utils/resolveMailbox.js +52 -0
- package/dist/utils/selectFields.js +83 -0
- package/package.json +47 -0
package/README.md
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
# @teamnetwork-nz/m365-mcp-server
|
|
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.
|
|
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.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Prerequisites
|
|
10
|
+
|
|
11
|
+
- Node.js 18+
|
|
12
|
+
- A Microsoft 365 tenant with an **Azure AD app registration** configured for app-only access (see [Admin Setup](#admin-setup) below)
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install -g @teamnetwork-nz/m365-mcp-server
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Or run directly without installing:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
npx @teamnetwork-nz/m365-mcp-server
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## Configuration
|
|
31
|
+
|
|
32
|
+
Create a JSON config file (e.g. `m365-config.json`) based on the example below. **Keep this file secure — it contains your client secret.**
|
|
33
|
+
|
|
34
|
+
```json
|
|
35
|
+
{
|
|
36
|
+
"connection": {
|
|
37
|
+
"tenantId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
|
|
38
|
+
"clientId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
|
|
39
|
+
"clientSecret": "your-client-secret"
|
|
40
|
+
},
|
|
41
|
+
"accounts": [
|
|
42
|
+
{
|
|
43
|
+
"id": "main",
|
|
44
|
+
"displayName": "Main Organisation",
|
|
45
|
+
"mailboxes": [
|
|
46
|
+
{ "email": "user@org.com", "readonly": false },
|
|
47
|
+
{ "email": "shared@org.com", "readonly": true, "displayName": "Shared (read-only)" }
|
|
48
|
+
]
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
"id": "partner",
|
|
52
|
+
"displayName": "Partner Tenant",
|
|
53
|
+
"tenantId": "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy",
|
|
54
|
+
"clientId": "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy",
|
|
55
|
+
"clientSecret": "partner-secret",
|
|
56
|
+
"mailboxes": [
|
|
57
|
+
{ "email": "partner@other.com", "readonly": false }
|
|
58
|
+
]
|
|
59
|
+
}
|
|
60
|
+
]
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Config notes
|
|
65
|
+
|
|
66
|
+
- The top-level `connection` block provides default credentials for all accounts.
|
|
67
|
+
- Each account can override `tenantId`, `clientId`, and/or `clientSecret` individually — useful for multi-tenant setups.
|
|
68
|
+
- `readonly: true` mailboxes block all write operations (send, reply, move, create/update events) at the server level.
|
|
69
|
+
|
|
70
|
+
Set the path to your config via the `M365_CONFIG_PATH` environment variable:
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
export M365_CONFIG_PATH=/path/to/m365-config.json
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
---
|
|
77
|
+
|
|
78
|
+
## Datetime & Timezone Handling
|
|
79
|
+
|
|
80
|
+
All datetime inputs and outputs are automatically converted to and from your local timezone — you never need to think about UTC.
|
|
81
|
+
|
|
82
|
+
### Input
|
|
83
|
+
|
|
84
|
+
Supply datetimes in your local time using ISO 8601 format. A timezone offset is optional:
|
|
85
|
+
|
|
86
|
+
```
|
|
87
|
+
2024-01-15T09:00:00 # naive — interpreted as your configured local timezone
|
|
88
|
+
2024-01-15T09:00:00+13:00 # explicit offset — converted to the configured timezone
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### Output
|
|
92
|
+
|
|
93
|
+
All dates returned by the server (email `receivedDateTime`, event `start`/`end`, etc.) are expressed in the configured timezone with their UTC offset, e.g. `2024-01-15T09:00:00+13:00`.
|
|
94
|
+
|
|
95
|
+
### Configuration
|
|
96
|
+
|
|
97
|
+
Set `DATETIME_FORMAT` in your environment:
|
|
98
|
+
|
|
99
|
+
| Value | Behaviour |
|
|
100
|
+
|---|---|
|
|
101
|
+
| `local` *(default)* | Use the server process's system local timezone |
|
|
102
|
+
| Any IANA timezone name | Use that timezone, e.g. `Pacific/Auckland`, `America/New_York` |
|
|
103
|
+
| `UTC` | No conversion — all datetimes are passed through in UTC as-is |
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
export DATETIME_FORMAT=Pacific/Auckland
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Or in your Claude Desktop MCP config:
|
|
110
|
+
|
|
111
|
+
```json
|
|
112
|
+
{
|
|
113
|
+
"mcpServers": {
|
|
114
|
+
"m365": {
|
|
115
|
+
"command": "npx",
|
|
116
|
+
"args": ["@teamnetwork-nz/m365-mcp-server"],
|
|
117
|
+
"env": {
|
|
118
|
+
"M365_CONFIG_PATH": "/path/to/m365-config.json",
|
|
119
|
+
"DATETIME_FORMAT": "Pacific/Auckland"
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## Claude Desktop / Claude Code Setup
|
|
129
|
+
|
|
130
|
+
Add the following to your Claude Desktop config (`claude_desktop_config.json`):
|
|
131
|
+
|
|
132
|
+
```json
|
|
133
|
+
{
|
|
134
|
+
"mcpServers": {
|
|
135
|
+
"m365": {
|
|
136
|
+
"command": "npx",
|
|
137
|
+
"args": ["@teamnetwork-nz/m365-mcp-server"],
|
|
138
|
+
"env": {
|
|
139
|
+
"M365_CONFIG_PATH": "/path/to/m365-config.json"
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
If installed globally, you can use the `m365-mcp` command instead:
|
|
147
|
+
|
|
148
|
+
```json
|
|
149
|
+
{
|
|
150
|
+
"mcpServers": {
|
|
151
|
+
"m365": {
|
|
152
|
+
"command": "m365-mcp",
|
|
153
|
+
"env": {
|
|
154
|
+
"M365_CONFIG_PATH": "/path/to/m365-config.json"
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
---
|
|
162
|
+
|
|
163
|
+
## Default Mailbox Behaviour
|
|
164
|
+
|
|
165
|
+
All email and calendar tools accept optional `accountId` and `mailbox` parameters. When either is omitted:
|
|
166
|
+
|
|
167
|
+
- **`accountId`** defaults to the first account in the config file.
|
|
168
|
+
- **`mailbox`** defaults to the first mailbox listed under the resolved account.
|
|
169
|
+
|
|
170
|
+
Config file ordering is the source of truth — put your primary account and mailbox first. Use `list_mailboxes` to see which account and mailbox are marked `isDefault: true`.
|
|
171
|
+
|
|
172
|
+
Operations always target exactly one mailbox per request, either the default or a specific one provided by name.
|
|
173
|
+
|
|
174
|
+
---
|
|
175
|
+
|
|
176
|
+
## Available Tools
|
|
177
|
+
|
|
178
|
+
### Email
|
|
179
|
+
|
|
180
|
+
| Tool | Description |
|
|
181
|
+
|---|---|
|
|
182
|
+
| `list_mailboxes` | List configured accounts and mailboxes with read/write status |
|
|
183
|
+
| `list_folders` | List mail folders (top-level or child folders) |
|
|
184
|
+
| `list_messages` | List messages with optional filters: date range, subject, body keyword, sender |
|
|
185
|
+
| `get_message` | Get full message details. Set `includeBody`, `includeAttachments`, or `includeInternetMessageHeaders` as needed |
|
|
186
|
+
| `send_message` | Send an email (non-readonly mailboxes only) |
|
|
187
|
+
| `reply_message` | Reply or reply-all to a message (non-readonly mailboxes only) |
|
|
188
|
+
| `move_message` | Move a message to another folder (non-readonly mailboxes only) |
|
|
189
|
+
| `list_message_attachments` | List all attachments on a message (file, item, and reference types) |
|
|
190
|
+
| `download_attachment` | Download a file attachment as base64. Images returned as MCP image content; reference attachments return their preview URL |
|
|
191
|
+
|
|
192
|
+
### Calendar
|
|
193
|
+
|
|
194
|
+
| Tool | Description |
|
|
195
|
+
|---|---|
|
|
196
|
+
| `list_calendars` | List calendars for a mailbox |
|
|
197
|
+
| `list_events` | List events in a date range (recurring events expanded into instances) |
|
|
198
|
+
| `get_event` | Get full event details |
|
|
199
|
+
| `create_event` | Create a new event (non-readonly mailboxes only) |
|
|
200
|
+
| `update_event` | Update an existing event (non-readonly mailboxes only) |
|
|
201
|
+
|
|
202
|
+
---
|
|
203
|
+
|
|
204
|
+
## Admin Setup
|
|
205
|
+
|
|
206
|
+
Before the server can access mailboxes, a tenant admin must complete the following steps.
|
|
207
|
+
|
|
208
|
+
### 1. Register an Azure AD Application
|
|
209
|
+
|
|
210
|
+
In the [Azure Portal](https://portal.azure.com) → **App registrations → New registration**:
|
|
211
|
+
|
|
212
|
+
- Set a name (e.g. `M365 MCP Server`)
|
|
213
|
+
- Note the **Application (client) ID** and **Directory (tenant) ID**
|
|
214
|
+
- Under **Certificates & secrets**, create a client secret and note the value
|
|
215
|
+
|
|
216
|
+
Grant the following **Application permissions** (not Delegated) and click **Grant admin consent**:
|
|
217
|
+
|
|
218
|
+
| Permission | Required for |
|
|
219
|
+
|---|---|
|
|
220
|
+
| `Mail.Read` | Reading email |
|
|
221
|
+
| `Mail.ReadWrite` | Moving messages |
|
|
222
|
+
| `Mail.Send` | Sending and replying |
|
|
223
|
+
| `Calendars.Read` | Reading calendar events |
|
|
224
|
+
| `Calendars.ReadWrite` | Creating and updating events |
|
|
225
|
+
|
|
226
|
+
### 2. Restrict Mailbox Access (Recommended)
|
|
227
|
+
|
|
228
|
+
By default, the above permissions grant access to **all mailboxes** in the tenant. Use an `ApplicationAccessPolicy` in Exchange Online to restrict access to only the mailboxes in your config.
|
|
229
|
+
|
|
230
|
+
Run the following in **Exchange Online PowerShell**:
|
|
231
|
+
|
|
232
|
+
```powershell
|
|
233
|
+
# Create a mail-enabled security group and add the allowed mailboxes
|
|
234
|
+
New-DistributionGroup -Name "MCP-Allowed-Mailboxes" -Type Security
|
|
235
|
+
Add-DistributionGroupMember -Identity "MCP-Allowed-Mailboxes" -Member "user@org.com"
|
|
236
|
+
Add-DistributionGroupMember -Identity "MCP-Allowed-Mailboxes" -Member "shared@org.com"
|
|
237
|
+
|
|
238
|
+
# Restrict the app to only those mailboxes
|
|
239
|
+
New-ApplicationAccessPolicy `
|
|
240
|
+
-AppId "<your-client-id>" `
|
|
241
|
+
-PolicyScopeGroupId "MCP-Allowed-Mailboxes" `
|
|
242
|
+
-AccessRight RestrictAccess `
|
|
243
|
+
-Description "Restrict MCP server to configured mailboxes"
|
|
244
|
+
|
|
245
|
+
# Verify (should return Granted for allowed mailboxes)
|
|
246
|
+
Test-ApplicationAccessPolicy -AppId "<your-client-id>" -Identity "user@org.com"
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
> **Note:** Policy changes can take up to 1 hour to propagate. Shared mailboxes must be added to the group directly.
|
|
250
|
+
|
|
251
|
+
---
|
|
252
|
+
|
|
253
|
+
## Security
|
|
254
|
+
|
|
255
|
+
- Credentials are never logged. The server scrubs secrets, tokens, and email body content from all log output.
|
|
256
|
+
- All Graph API calls use the `/users/{email}/...` path (application permissions), never `/me/`.
|
|
257
|
+
- Write operations are blocked at the server level for any mailbox marked `readonly: true` in the config — this check happens before any network call is made.
|
|
258
|
+
- The config file should be kept outside your project directory and never committed to source control. Use restrictive file permissions (`chmod 600` on Linux/macOS).
|
|
259
|
+
|
|
260
|
+
---
|
|
261
|
+
|
|
262
|
+
## License
|
|
263
|
+
|
|
264
|
+
MIT
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"connection": {
|
|
3
|
+
"tenantId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
|
|
4
|
+
"clientId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
|
|
5
|
+
"clientSecret": "your-default-client-secret"
|
|
6
|
+
},
|
|
7
|
+
"accounts": [
|
|
8
|
+
{
|
|
9
|
+
"id": "main",
|
|
10
|
+
"displayName": "Main Organisation",
|
|
11
|
+
"mailboxes": [
|
|
12
|
+
{ "email": "user@org.com", "readonly": false, "displayName": "Primary User" },
|
|
13
|
+
{ "email": "shared@org.com", "readonly": true, "displayName": "Shared Mailbox (read-only)" }
|
|
14
|
+
]
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
"id": "partner",
|
|
18
|
+
"displayName": "Partner Tenant",
|
|
19
|
+
"tenantId": "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy",
|
|
20
|
+
"clientId": "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy",
|
|
21
|
+
"clientSecret": "partner-specific-secret",
|
|
22
|
+
"mailboxes": [
|
|
23
|
+
{ "email": "partner@other.com", "readonly": false }
|
|
24
|
+
]
|
|
25
|
+
}
|
|
26
|
+
]
|
|
27
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { ToolError } from '../utils/errors.js';
|
|
2
|
+
const GRAPH_SCOPE = 'https://graph.microsoft.com/.default';
|
|
3
|
+
export class AuthManager {
|
|
4
|
+
cache;
|
|
5
|
+
constructor(cache) {
|
|
6
|
+
this.cache = cache;
|
|
7
|
+
}
|
|
8
|
+
async getAccessToken(accountId) {
|
|
9
|
+
const client = this.cache.getClient(accountId);
|
|
10
|
+
const result = await client.acquireTokenByClientCredential({
|
|
11
|
+
scopes: [GRAPH_SCOPE],
|
|
12
|
+
});
|
|
13
|
+
if (!result?.accessToken) {
|
|
14
|
+
throw new ToolError(`Failed to acquire access token for account "${accountId}" — check tenant ID, client ID, and client secret`, 'AUTH_FAILED');
|
|
15
|
+
}
|
|
16
|
+
// Token value is intentionally not logged — see utils/logger.ts scrubbing rules
|
|
17
|
+
return result.accessToken;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { ConfidentialClientApplication } from '@azure/msal-node';
|
|
2
|
+
import { resolveCredentials } from '../config/loader.js';
|
|
3
|
+
export class TokenCache {
|
|
4
|
+
clients = new Map();
|
|
5
|
+
constructor(config) {
|
|
6
|
+
for (const account of config.accounts) {
|
|
7
|
+
const creds = resolveCredentials(config, account);
|
|
8
|
+
this.clients.set(account.id, new ConfidentialClientApplication({
|
|
9
|
+
auth: {
|
|
10
|
+
clientId: creds.clientId,
|
|
11
|
+
clientSecret: creds.clientSecret,
|
|
12
|
+
authority: `https://login.microsoftonline.com/${creds.tenantId}`,
|
|
13
|
+
},
|
|
14
|
+
// No cache plugin = default in-memory cache only (no disk persistence)
|
|
15
|
+
}));
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
getClient(accountId) {
|
|
19
|
+
const client = this.clients.get(accountId);
|
|
20
|
+
if (!client) {
|
|
21
|
+
throw new Error(`Unknown account ID: "${accountId}". Check your config file.`);
|
|
22
|
+
}
|
|
23
|
+
return client;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { readFileSync } from 'fs';
|
|
2
|
+
import { AppConfigSchema } from './schema.js';
|
|
3
|
+
export function loadConfig() {
|
|
4
|
+
const configPath = process.env['M365_CONFIG_PATH'];
|
|
5
|
+
if (!configPath) {
|
|
6
|
+
throw new Error('M365_CONFIG_PATH environment variable is not set');
|
|
7
|
+
}
|
|
8
|
+
let raw;
|
|
9
|
+
try {
|
|
10
|
+
raw = JSON.parse(readFileSync(configPath, 'utf-8'));
|
|
11
|
+
}
|
|
12
|
+
catch (err) {
|
|
13
|
+
throw new Error(`Failed to read config file at "${configPath}": ${err.message}`);
|
|
14
|
+
}
|
|
15
|
+
const result = AppConfigSchema.safeParse(raw);
|
|
16
|
+
if (!result.success) {
|
|
17
|
+
const issues = result.error.issues
|
|
18
|
+
.map((i) => ` - ${i.path.join('.')}: ${i.message}`)
|
|
19
|
+
.join('\n');
|
|
20
|
+
throw new Error(`Config validation failed:\n${issues}`);
|
|
21
|
+
}
|
|
22
|
+
return Object.freeze(result.data);
|
|
23
|
+
}
|
|
24
|
+
/** Merge connection defaults with per-account overrides. Account fields win. */
|
|
25
|
+
export function resolveCredentials(config, account) {
|
|
26
|
+
return {
|
|
27
|
+
tenantId: account.tenantId ?? config.connection.tenantId,
|
|
28
|
+
clientId: account.clientId ?? config.connection.clientId,
|
|
29
|
+
clientSecret: account.clientSecret ?? config.connection.clientSecret,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export const ConnectionConfigSchema = z.object({
|
|
3
|
+
tenantId: z.string().uuid('connection.tenantId must be a valid UUID'),
|
|
4
|
+
clientId: z.string().uuid('connection.clientId must be a valid UUID'),
|
|
5
|
+
clientSecret: z.string().min(1, 'connection.clientSecret must not be empty'),
|
|
6
|
+
});
|
|
7
|
+
export const MailboxConfigSchema = z.object({
|
|
8
|
+
email: z.string().email('mailbox.email must be a valid email address'),
|
|
9
|
+
readonly: z.boolean(),
|
|
10
|
+
displayName: z.string().optional(),
|
|
11
|
+
});
|
|
12
|
+
export const AccountConfigSchema = z.object({
|
|
13
|
+
id: z.string().min(1, 'account.id must not be empty'),
|
|
14
|
+
displayName: z.string().optional(),
|
|
15
|
+
tenantId: z.string().uuid().optional(),
|
|
16
|
+
clientId: z.string().uuid().optional(),
|
|
17
|
+
clientSecret: z.string().min(1).optional(),
|
|
18
|
+
mailboxes: z.array(MailboxConfigSchema).min(1, 'Each account must have at least one mailbox'),
|
|
19
|
+
});
|
|
20
|
+
export const AppConfigSchema = z.object({
|
|
21
|
+
connection: ConnectionConfigSchema,
|
|
22
|
+
accounts: z.array(AccountConfigSchema).min(1, 'Config must have at least one account'),
|
|
23
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { mapGraphError } from '../utils/errors.js';
|
|
2
|
+
// ── Helpers ────────────────────────────────────────────────────────────────
|
|
3
|
+
function deriveAttachmentType(odataType) {
|
|
4
|
+
if (odataType?.includes('referenceAttachment'))
|
|
5
|
+
return 'referenceAttachment';
|
|
6
|
+
if (odataType?.includes('itemAttachment'))
|
|
7
|
+
return 'itemAttachment';
|
|
8
|
+
return 'fileAttachment';
|
|
9
|
+
}
|
|
10
|
+
function normaliseAttachment(raw) {
|
|
11
|
+
const odataType = raw['@odata.type'];
|
|
12
|
+
const attachmentType = deriveAttachmentType(odataType);
|
|
13
|
+
const meta = {
|
|
14
|
+
id: raw['id'],
|
|
15
|
+
name: raw['name'],
|
|
16
|
+
contentType: raw['contentType'] ?? 'application/octet-stream',
|
|
17
|
+
size: raw['size'] ?? 0,
|
|
18
|
+
isInline: raw['isInline'] ?? false,
|
|
19
|
+
attachmentType,
|
|
20
|
+
};
|
|
21
|
+
if (attachmentType === 'referenceAttachment' && raw['previewUrl']) {
|
|
22
|
+
meta.previewUrl = raw['previewUrl'];
|
|
23
|
+
}
|
|
24
|
+
return meta;
|
|
25
|
+
}
|
|
26
|
+
// ── API calls ──────────────────────────────────────────────────────────────
|
|
27
|
+
export async function listAttachments(client, email, messageId) {
|
|
28
|
+
try {
|
|
29
|
+
const response = await client
|
|
30
|
+
.api(`/users/${email}/messages/${messageId}/attachments`)
|
|
31
|
+
.select('id,name,contentType,size,isInline,previewUrl')
|
|
32
|
+
.get();
|
|
33
|
+
return (response.value ?? []).map(normaliseAttachment);
|
|
34
|
+
}
|
|
35
|
+
catch (err) {
|
|
36
|
+
throw mapGraphError(err, 'list_message_attachments');
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export async function downloadAttachment(client, email, messageId, attachmentId) {
|
|
40
|
+
try {
|
|
41
|
+
// Fetch the full attachment record including contentBytes for file attachments.
|
|
42
|
+
// contentBytes is already base64-encoded by the Graph API.
|
|
43
|
+
const raw = await client
|
|
44
|
+
.api(`/users/${email}/messages/${messageId}/attachments/${attachmentId}`)
|
|
45
|
+
.select('id,name,contentType,isInline,contentBytes,previewUrl,@odata.type')
|
|
46
|
+
.get();
|
|
47
|
+
const attachmentType = deriveAttachmentType(raw['@odata.type']);
|
|
48
|
+
if (attachmentType === 'referenceAttachment') {
|
|
49
|
+
return {
|
|
50
|
+
kind: 'reference',
|
|
51
|
+
previewUrl: raw['previewUrl'] ?? raw['name'],
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
if (attachmentType === 'itemAttachment') {
|
|
55
|
+
return {
|
|
56
|
+
kind: 'item',
|
|
57
|
+
name: raw['name'],
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
// fileAttachment — contentBytes is already base64 from Graph
|
|
61
|
+
return {
|
|
62
|
+
kind: 'file',
|
|
63
|
+
name: raw['name'],
|
|
64
|
+
mimeType: raw['contentType'] ?? 'application/octet-stream',
|
|
65
|
+
contentBytes: raw['contentBytes'],
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
catch (err) {
|
|
69
|
+
throw mapGraphError(err, 'download_attachment');
|
|
70
|
+
}
|
|
71
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { mapGraphError } from '../utils/errors.js';
|
|
2
|
+
export async function listCalendars(client, email) {
|
|
3
|
+
try {
|
|
4
|
+
return await client
|
|
5
|
+
.api(`/users/${email}/calendars`)
|
|
6
|
+
.select('id,name,canEdit,color,isDefaultCalendar')
|
|
7
|
+
.get();
|
|
8
|
+
}
|
|
9
|
+
catch (err) {
|
|
10
|
+
throw mapGraphError(err, 'list_calendars');
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export async function listEvents(client, email, params) {
|
|
14
|
+
try {
|
|
15
|
+
// calendarView expands recurring events into individual instances within the window
|
|
16
|
+
const basePath = params.calendarId
|
|
17
|
+
? `/users/${email}/calendars/${params.calendarId}/calendarView`
|
|
18
|
+
: `/users/${email}/calendarView`;
|
|
19
|
+
return await client
|
|
20
|
+
.api(basePath)
|
|
21
|
+
.query({
|
|
22
|
+
startDateTime: params.startDate,
|
|
23
|
+
endDateTime: params.endDate,
|
|
24
|
+
})
|
|
25
|
+
.select(params.select)
|
|
26
|
+
.top(params.maxResults)
|
|
27
|
+
.orderby('start/dateTime')
|
|
28
|
+
.get();
|
|
29
|
+
}
|
|
30
|
+
catch (err) {
|
|
31
|
+
throw mapGraphError(err, 'list_events');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
export async function getEvent(client, email, eventId) {
|
|
35
|
+
try {
|
|
36
|
+
return await client
|
|
37
|
+
.api(`/users/${email}/events/${eventId}`)
|
|
38
|
+
.select('id,subject,body,start,end,location,organizer,attendees,isOnlineMeeting,onlineMeeting,recurrence')
|
|
39
|
+
.get();
|
|
40
|
+
}
|
|
41
|
+
catch (err) {
|
|
42
|
+
throw mapGraphError(err, 'get_event');
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export async function createEvent(client, email, params) {
|
|
46
|
+
try {
|
|
47
|
+
const basePath = params.calendarId
|
|
48
|
+
? `/users/${email}/calendars/${params.calendarId}/events`
|
|
49
|
+
: `/users/${email}/events`;
|
|
50
|
+
const attendees = (params.attendees ?? []).map((addr) => ({
|
|
51
|
+
emailAddress: { address: addr },
|
|
52
|
+
type: 'required',
|
|
53
|
+
}));
|
|
54
|
+
const body = {
|
|
55
|
+
subject: params.subject,
|
|
56
|
+
start: { dateTime: params.startTime, timeZone: params.timeZone },
|
|
57
|
+
end: { dateTime: params.endTime, timeZone: params.timeZone },
|
|
58
|
+
isOnlineMeeting: params.isOnlineMeeting,
|
|
59
|
+
};
|
|
60
|
+
if (params.body !== undefined) {
|
|
61
|
+
body['body'] = {
|
|
62
|
+
contentType: params.bodyType === 'html' ? 'HTML' : 'Text',
|
|
63
|
+
content: params.body,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
if (params.location) {
|
|
67
|
+
body['location'] = { displayName: params.location };
|
|
68
|
+
}
|
|
69
|
+
if (attendees.length > 0) {
|
|
70
|
+
body['attendees'] = attendees;
|
|
71
|
+
}
|
|
72
|
+
return await client.api(basePath).post(body);
|
|
73
|
+
}
|
|
74
|
+
catch (err) {
|
|
75
|
+
throw mapGraphError(err, 'create_event');
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
export async function updateEvent(client, email, eventId, params) {
|
|
79
|
+
try {
|
|
80
|
+
const patch = {};
|
|
81
|
+
if (params.subject !== undefined)
|
|
82
|
+
patch['subject'] = params.subject;
|
|
83
|
+
if (params.body !== undefined) {
|
|
84
|
+
patch['body'] = {
|
|
85
|
+
contentType: (params.bodyType ?? 'text') === 'html' ? 'HTML' : 'Text',
|
|
86
|
+
content: params.body,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
if (params.startTime !== undefined) {
|
|
90
|
+
patch['start'] = { dateTime: params.startTime, timeZone: params.timeZone ?? 'UTC' };
|
|
91
|
+
}
|
|
92
|
+
if (params.endTime !== undefined) {
|
|
93
|
+
patch['end'] = { dateTime: params.endTime, timeZone: params.timeZone ?? 'UTC' };
|
|
94
|
+
}
|
|
95
|
+
if (params.location !== undefined) {
|
|
96
|
+
patch['location'] = { displayName: params.location };
|
|
97
|
+
}
|
|
98
|
+
if (params.attendees !== undefined) {
|
|
99
|
+
patch['attendees'] = params.attendees.map((addr) => ({
|
|
100
|
+
emailAddress: { address: addr },
|
|
101
|
+
type: 'required',
|
|
102
|
+
}));
|
|
103
|
+
}
|
|
104
|
+
return await client.api(`/users/${email}/events/${eventId}`).patch(patch);
|
|
105
|
+
}
|
|
106
|
+
catch (err) {
|
|
107
|
+
throw mapGraphError(err, 'update_event');
|
|
108
|
+
}
|
|
109
|
+
}
|