@softeria/ms-365-mcp-server 0.185.1 → 0.187.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.
@@ -0,0 +1,341 @@
1
+ /* global createMcpAppBridge */
2
+
3
+ (() => {
4
+ 'use strict';
5
+
6
+ // Long enough for an approval prompt in the host; each progress notification starts it over
7
+ const CALL_TIMEOUT_MS = 10 * 60 * 1000;
8
+ // Bidi controls and marks can make text read in another order than it is sent: one
9
+ // address like another, or the digit groups of an account number swapped
10
+ const BIDI = /[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/g;
11
+
12
+ let config = {};
13
+ try {
14
+ config = JSON.parse(document.getElementById('mcp-app-config').textContent) || {};
15
+ } catch {
16
+ // Unfilled placeholder: the view can still show the draft, just not send it
17
+ }
18
+ // Role -> tool name, and only for tools this server has registered
19
+ const tools = isObject(config.tools) ? config.tools : {};
20
+
21
+ const els = {
22
+ subject: document.getElementById('subject'),
23
+ fields: document.getElementById('fields'),
24
+ body: document.getElementById('body'),
25
+ send: document.getElementById('send'),
26
+ open: document.getElementById('open'),
27
+ status: document.getElementById('status'),
28
+ };
29
+
30
+ const state = {
31
+ // Arguments of the tool call that created the draft
32
+ input: undefined,
33
+ draft: undefined,
34
+ // Whether the draft shown is one the view read itself
35
+ read: false,
36
+ reading: false,
37
+ sending: false,
38
+ sent: false,
39
+ error: undefined,
40
+ notice: undefined,
41
+ };
42
+
43
+ const bridge = createMcpAppBridge({
44
+ name: 'ms-365-mail-draft',
45
+ onToolInput(args) {
46
+ state.input = args;
47
+ },
48
+ onToolResult(result) {
49
+ try {
50
+ const draft = bridge.readToolResult(result, 'Creating the draft failed.');
51
+ if (!isObject(draft) || !str(draft.id)) {
52
+ throw new Error('The result does not include the draft, so it is not shown here.');
53
+ }
54
+ state.draft = draft;
55
+ } catch (error) {
56
+ state.error = error.message;
57
+ }
58
+ render();
59
+ readOnOpen();
60
+ },
61
+ onToolCancelled() {
62
+ state.error = 'Creating the draft was cancelled.';
63
+ render();
64
+ },
65
+ onReady() {
66
+ render();
67
+ readOnOpen();
68
+ },
69
+ onInitError(error) {
70
+ state.error = 'Could not connect to the host: ' + error.message;
71
+ render();
72
+ },
73
+ });
74
+
75
+ els.send.addEventListener('click', send);
76
+ els.open.addEventListener('click', openInOutlook);
77
+
78
+ // The view shows the draft as it reads it itself, not the result that opened it: a select in
79
+ // the model's call can leave fields out of that, and only a read gets Graph's text of the body
80
+ async function readOnOpen() {
81
+ if (!state.draft || state.read || state.reading || !canRead()) return;
82
+ state.reading = true;
83
+ render();
84
+ try {
85
+ const current = await readDraft();
86
+ if (current.isDraft === false) throw new Error('This draft has already been sent.');
87
+ state.draft = current;
88
+ state.read = true;
89
+ } catch (error) {
90
+ state.error = (error && error.message) || String(error);
91
+ }
92
+ state.reading = false;
93
+ render();
94
+ }
95
+
96
+ async function send() {
97
+ if (!canSend()) return;
98
+ state.sending = true;
99
+ state.error = undefined;
100
+ state.notice = undefined;
101
+ render();
102
+ try {
103
+ // The click approves what the user saw, so the draft is read again first. When it
104
+ // changed since (the model edited it, or an old view is shown again), or the view had
105
+ // not read it yet, that version is shown instead and sending takes another click.
106
+ const current = await readDraft();
107
+ if (current.isDraft === false) throw new Error('This draft has already been sent.');
108
+ if (
109
+ !state.read ||
110
+ !str(state.draft.changeKey) ||
111
+ current.changeKey !== state.draft.changeKey
112
+ ) {
113
+ state.notice = state.read
114
+ ? 'The draft changed since it was shown. Check it and press Send again.'
115
+ : 'Here is the whole draft. Check it and press Send again.';
116
+ state.draft = current;
117
+ state.read = true;
118
+ } else if (hasRecipients(current)) {
119
+ // confirm is the click itself, the user's approval that the confirm gate asks for
120
+ const result = await bridge.callTool(tools.send, mailboxArgs({ confirm: true }), {
121
+ timeout: CALL_TIMEOUT_MS,
122
+ });
123
+ const error = bridge.toolError(result, 'Sending failed.');
124
+ if (error) throw new Error(error);
125
+ state.sent = true;
126
+ tellModel();
127
+ }
128
+ } catch (error) {
129
+ state.error =
130
+ error && error.name === 'TimeoutError'
131
+ ? 'No answer from the host. Check Sent Items before you try again.'
132
+ : (error && error.message) || String(error);
133
+ }
134
+ state.sending = false;
135
+ render();
136
+ }
137
+
138
+ async function readDraft() {
139
+ const result = await bridge.callTool(tools.get, mailboxArgs({}), {
140
+ timeout: CALL_TIMEOUT_MS,
141
+ });
142
+ const draft = bridge.readToolResult(result, 'Reading the draft failed.');
143
+ if (!isObject(draft) || draft.id !== state.draft.id) {
144
+ throw new Error('This result is not the draft.');
145
+ }
146
+ return draft;
147
+ }
148
+
149
+ // The draft's own id, in the mailbox it was created in: for a reply or forward draft, the
150
+ // input's messageId is the mail it answers
151
+ function mailboxArgs(extra) {
152
+ const input = state.input || {};
153
+ const args = Object.assign({ messageId: state.draft.id }, extra);
154
+ const userId = str(input.userId) || str(input['user-id']);
155
+ if (userId) args.userId = userId;
156
+ const account = str(input.account);
157
+ if (account) args.account = account;
158
+ return args;
159
+ }
160
+
161
+ // So the model does not offer to send it again. No subject: a reply's comes from outside.
162
+ function tellModel() {
163
+ if (!bridge.capabilities.updateModelContext) return;
164
+ bridge
165
+ .updateModelContext(
166
+ 'The user sent the draft with id ' +
167
+ state.draft.id +
168
+ ' from the mail view. It is in Sent Items now, so it can no longer be sent or changed as a draft.'
169
+ )
170
+ .catch(() => {});
171
+ }
172
+
173
+ async function openInOutlook() {
174
+ const url = webLink(state.draft);
175
+ if (!url) return;
176
+ try {
177
+ const result = await bridge.openLink(url);
178
+ if (result && result.isError) throw new Error('The host did not open the link.');
179
+ } catch (error) {
180
+ state.error = error.message || 'The host did not open the link.';
181
+ render();
182
+ }
183
+ }
184
+
185
+ function render() {
186
+ const draft = state.draft;
187
+ if (draft) {
188
+ els.subject.textContent = clean(draft.subject) || '(no subject)';
189
+ els.fields.replaceChildren(...fields(draft));
190
+ const body = bodyText(draft);
191
+ els.body.textContent = body;
192
+ els.body.hidden = !body;
193
+ }
194
+ const openable = Boolean(draft && !state.sent && webLink(draft) && canOpenLinks());
195
+ els.send.hidden = !sendable();
196
+ els.send.disabled = !canSend();
197
+ els.open.hidden = !openable;
198
+ if (state.error) setStatus(state.error, true);
199
+ else if (!draft) setStatus('Loading...', false);
200
+ else if (state.sent) setStatus('Sent.', false);
201
+ else if (state.sending) setStatus('Sending...', false);
202
+ else if (state.reading) setStatus('Reading the draft...', false);
203
+ else if (!sendable()) {
204
+ setStatus(
205
+ openable
206
+ ? 'To send it, open it in Outlook or ask in the chat.'
207
+ : 'Ask in the chat to send it.',
208
+ false
209
+ );
210
+ } else if (!hasRecipients(draft)) setStatus('This draft has no recipients yet.', false);
211
+ else if (state.notice) setStatus(state.notice, false);
212
+ else setStatus('', false);
213
+ }
214
+
215
+ function fields(draft) {
216
+ const rows = [];
217
+ const from = recipientText(draft.from);
218
+ if (from) rows.push(...field('From', from));
219
+ rows.push(...field('To', recipientsText(draft.toRecipients) || 'Nobody yet'));
220
+ const cc = recipientsText(draft.ccRecipients);
221
+ if (cc) rows.push(...field('Cc', cc));
222
+ const bcc = recipientsText(draft.bccRecipients);
223
+ if (bcc) rows.push(...field('Bcc', bcc));
224
+ // A draft can send the answers to someone else
225
+ const replyTo = recipientsText(draft.replyTo);
226
+ if (replyTo) rows.push(...field('Reply to', replyTo));
227
+ if (draft.hasAttachments === true) rows.push(...field('Attachments', 'Yes'));
228
+ return rows;
229
+ }
230
+
231
+ function field(label, value) {
232
+ return [span('label', label), span('value', value)];
233
+ }
234
+
235
+ // Every address is written out: a display name alone can claim to be anyone
236
+ function recipientText(recipient) {
237
+ const email =
238
+ isObject(recipient) && isObject(recipient.emailAddress) ? recipient.emailAddress : {};
239
+ const address = clean(email.address);
240
+ const name = clean(email.name);
241
+ if (!address) return name ? name + ' (no address)' : '';
242
+ return name && name.toLowerCase() !== address.toLowerCase()
243
+ ? name + ' <' + address + '>'
244
+ : address;
245
+ }
246
+
247
+ function recipientsText(list) {
248
+ return Array.isArray(list) ? list.map(recipientText).filter(Boolean).join(', ') : '';
249
+ }
250
+
251
+ function hasRecipients(draft) {
252
+ return ['toRecipients', 'ccRecipients', 'bccRecipients'].some(
253
+ (key) =>
254
+ Array.isArray(draft[key]) &&
255
+ draft[key].some(
256
+ (r) => isObject(r) && isObject(r.emailAddress) && clean(r.emailAddress.address)
257
+ )
258
+ );
259
+ }
260
+
261
+ // Bidi controls can make one address read like another, so they never reach the view
262
+ function clean(value) {
263
+ const text = str(value) && value.replace(BIDI, '').trim();
264
+ return text || undefined;
265
+ }
266
+
267
+ // This server asks Graph for text bodies, so the view's own read has the whole body as text,
268
+ // which in practice writes out link and image addresses. The view never turns HTML into text
269
+ // itself: before its read, or when the server gives HTML (MS365_MCP_BODY_FORMAT=html), it
270
+ // shows only Graph's preview of the first 255 characters.
271
+ function wholeBody(draft) {
272
+ const body = isObject(draft.body) ? draft.body : {};
273
+ return String(body.contentType).toLowerCase() === 'text' && typeof body.content === 'string';
274
+ }
275
+
276
+ // Without bidi controls and marks, the body reads in the order it is sent
277
+ function bodyText(draft) {
278
+ const text = wholeBody(draft) ? draft.body.content : str(draft.bodyPreview) || '';
279
+ return text.replace(BIDI, '').trim();
280
+ }
281
+
282
+ function webLink(draft) {
283
+ return draft ? httpsUrl(draft.webLink) : undefined;
284
+ }
285
+
286
+ // Send needs both tools, and once the view has read the draft, all of its body as text
287
+ function sendable() {
288
+ return Boolean(
289
+ state.draft && !state.sent && canCall() && (!state.read || wholeBody(state.draft))
290
+ );
291
+ }
292
+
293
+ // Without recipients a click still reads the draft again: the model may add them later
294
+ function canSend() {
295
+ return sendable() && !state.sending && !state.reading;
296
+ }
297
+
298
+ function canRead() {
299
+ return Boolean(bridge.capabilities.serverTools && str(tools.get));
300
+ }
301
+
302
+ // Sending needs both: the draft is read again right before it is sent
303
+ function canCall() {
304
+ return canRead() && Boolean(str(tools.send));
305
+ }
306
+
307
+ function canOpenLinks() {
308
+ return Boolean(bridge.capabilities.openLinks);
309
+ }
310
+
311
+ function span(className, text) {
312
+ const el = document.createElement('span');
313
+ el.className = className;
314
+ el.textContent = text;
315
+ return el;
316
+ }
317
+
318
+ function setStatus(text, isError) {
319
+ els.status.textContent = text;
320
+ els.status.hidden = !text;
321
+ els.status.classList.toggle('error', Boolean(isError));
322
+ }
323
+
324
+ function isObject(value) {
325
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
326
+ }
327
+
328
+ function str(value) {
329
+ return typeof value === 'string' && value ? value : undefined;
330
+ }
331
+
332
+ function httpsUrl(value) {
333
+ if (typeof value !== 'string') return undefined;
334
+ try {
335
+ const url = new URL(value);
336
+ return url.protocol === 'https:' ? url.href : undefined;
337
+ } catch {
338
+ return undefined;
339
+ }
340
+ }
341
+ })();
package/dist/cli.js CHANGED
@@ -98,6 +98,9 @@ program.name("ms-365-mcp-server").description("Microsoft 365 MCP Server").versio
98
98
  ).option(
99
99
  "--allow-unauthenticated-discovery",
100
100
  "In HTTP mode, allow MCP discovery requests (initialize, tools/list, prompts/list, resources/list, ping) without a bearer token, so a gateway can enumerate the tool catalog before any user has authenticated. Non-discovery requests (e.g. tools/call) still require a token. Off by default."
101
+ ).option(
102
+ "--enable-mcp-apps",
103
+ "(experimental) Show an interactive MCP Apps view for the tools that have one, in hosts that support MCP Apps: a OneDrive/SharePoint file browser for folder listings, and a mail draft view with a Send button for the draft tools. Other hosts ignore it. No effect with --toon. Equivalent env var: MS365_MCP_ENABLE_MCP_APPS=true."
101
104
  ).addOption(
102
105
  // DEPRECATED: kept only so existing deployments that set --base-url or
103
106
  // MS365_MCP_BASE_URL do not crash at startup. Use --public-url /
@@ -281,6 +284,9 @@ function parseArgs() {
281
284
  if (process.env.MS365_MCP_ALLOW_UNAUTHENTICATED_DISCOVERY === "true" || process.env.MS365_MCP_ALLOW_UNAUTHENTICATED_DISCOVERY === "1") {
282
285
  options.allowUnauthenticatedDiscovery = true;
283
286
  }
287
+ if (process.env.MS365_MCP_ENABLE_MCP_APPS === "true" || process.env.MS365_MCP_ENABLE_MCP_APPS === "1") {
288
+ options.enableMcpApps = true;
289
+ }
284
290
  if (options.cloud) {
285
291
  process.env.MS365_MCP_CLOUD_TYPE = options.cloud;
286
292
  }
@@ -128,7 +128,11 @@
128
128
  "toolName": "create-shared-mailbox-draft",
129
129
  "presets": ["work"],
130
130
  "workScopes": ["Mail.ReadWrite.Shared"],
131
- "appScopes": ["Mail.ReadWrite"]
131
+ "appScopes": ["Mail.ReadWrite"],
132
+ "mcpApp": {
133
+ "view": "mail-draft",
134
+ "tools": { "get": "get-shared-mailbox-message", "send": "send-shared-mailbox-draft" }
135
+ }
132
136
  },
133
137
  {
134
138
  "pathPattern": "/users/{user-id}/messages/{message-id}/move",
@@ -183,7 +187,11 @@
183
187
  "presets": ["work"],
184
188
  "workScopes": ["Mail.ReadWrite.Shared"],
185
189
  "appScopes": ["Mail.ReadWrite"],
186
- "llmTip": "Create a reply draft in a shared mailbox preserving thread metadata (conversationId, In-Reply-To, References). The 'user-id' is the shared mailbox email address (e.g. support@contoso.com). Does not send — use send-shared-mailbox-draft to send afterwards. Message.body (contentType 'html' for HTML) replaces the whole draft body, dropping the quoted history; 'comment' keeps it. Specifying both 'comment' and Message.body returns 400. Requires delegated access to the shared mailbox."
190
+ "llmTip": "Create a reply draft in a shared mailbox preserving thread metadata (conversationId, In-Reply-To, References). The 'user-id' is the shared mailbox email address (e.g. support@contoso.com). Does not send — use send-shared-mailbox-draft to send afterwards. Message.body (contentType 'html' for HTML) replaces the whole draft body, dropping the quoted history; 'comment' keeps it. Specifying both 'comment' and Message.body returns 400. Requires delegated access to the shared mailbox.",
191
+ "mcpApp": {
192
+ "view": "mail-draft",
193
+ "tools": { "get": "get-shared-mailbox-message", "send": "send-shared-mailbox-draft" }
194
+ }
187
195
  },
188
196
  {
189
197
  "pathPattern": "/users/{user-id}/messages/{message-id}/createReplyAll",
@@ -192,7 +200,11 @@
192
200
  "presets": ["work"],
193
201
  "workScopes": ["Mail.ReadWrite.Shared"],
194
202
  "appScopes": ["Mail.ReadWrite"],
195
- "llmTip": "Create a reply-all draft in a shared mailbox preserving thread metadata (conversationId, In-Reply-To, References). The 'user-id' is the shared mailbox email address. Does not send — use send-shared-mailbox-draft to send afterwards. Message.body (contentType 'html' for HTML) replaces the whole draft body, dropping the quoted history; 'comment' keeps it. Specifying both 'comment' and Message.body returns 400. Requires delegated access to the shared mailbox."
203
+ "llmTip": "Create a reply-all draft in a shared mailbox preserving thread metadata (conversationId, In-Reply-To, References). The 'user-id' is the shared mailbox email address. Does not send — use send-shared-mailbox-draft to send afterwards. Message.body (contentType 'html' for HTML) replaces the whole draft body, dropping the quoted history; 'comment' keeps it. Specifying both 'comment' and Message.body returns 400. Requires delegated access to the shared mailbox.",
204
+ "mcpApp": {
205
+ "view": "mail-draft",
206
+ "tools": { "get": "get-shared-mailbox-message", "send": "send-shared-mailbox-draft" }
207
+ }
196
208
  },
197
209
  {
198
210
  "pathPattern": "/users/{user-id}/messages/{message-id}/createForward",
@@ -201,7 +213,11 @@
201
213
  "presets": ["work"],
202
214
  "workScopes": ["Mail.ReadWrite.Shared"],
203
215
  "appScopes": ["Mail.ReadWrite"],
204
- "llmTip": "Create a forward draft in a shared mailbox without sending. The 'user-id' is the shared mailbox email address. Does not send — use send-shared-mailbox-draft to send afterwards. Useful when the user wants to review before the forward goes out. Requires delegated access to the shared mailbox."
216
+ "llmTip": "Create a forward draft in a shared mailbox without sending. The 'user-id' is the shared mailbox email address. Does not send — use send-shared-mailbox-draft to send afterwards. Useful when the user wants to review before the forward goes out. Requires delegated access to the shared mailbox.",
217
+ "mcpApp": {
218
+ "view": "mail-draft",
219
+ "tools": { "get": "get-shared-mailbox-message", "send": "send-shared-mailbox-draft" }
220
+ }
205
221
  },
206
222
  {
207
223
  "pathPattern": "/users/{user-id}/messages/{message-id}/send",
@@ -292,7 +308,11 @@
292
308
  "toolName": "create-draft-email",
293
309
  "descriptionOverride": "Create a draft Outlook email message in the signed-in user's Drafts folder. Set subject, body, toRecipients, ccRecipients, and importance. The draft is saved, not sent — use send-mail to send a message directly, or send the draft afterwards.",
294
310
  "presets": ["mail", "outlook", "personal"],
295
- "scopes": ["Mail.ReadWrite"]
311
+ "scopes": ["Mail.ReadWrite"],
312
+ "mcpApp": {
313
+ "view": "mail-draft",
314
+ "tools": { "get": "get-mail-message", "send": "send-draft-message" }
315
+ }
296
316
  },
297
317
  {
298
318
  "pathPattern": "/me/messages/{message-id}/move",
@@ -388,7 +408,11 @@
388
408
  "toolName": "create-forward-draft",
389
409
  "presets": ["mail", "outlook", "personal"],
390
410
  "scopes": ["Mail.ReadWrite"],
391
- "llmTip": "Create a forward draft (does not send). Useful when user wants to review before sending."
411
+ "llmTip": "Create a forward draft (does not send). Useful when user wants to review before sending.",
412
+ "mcpApp": {
413
+ "view": "mail-draft",
414
+ "tools": { "get": "get-mail-message", "send": "send-draft-message" }
415
+ }
392
416
  },
393
417
  {
394
418
  "pathPattern": "/me/messages/{message-id}/createReply",
@@ -396,7 +420,11 @@
396
420
  "toolName": "create-reply-draft",
397
421
  "presets": ["mail", "outlook", "personal"],
398
422
  "scopes": ["Mail.ReadWrite"],
399
- "llmTip": "Message.body (contentType 'html' for HTML) replaces the whole draft body, dropping the quoted history; 'comment' keeps it. Specifying both 'comment' and Message.body returns 400. Signatures are added by the Outlook client only, not via Graph."
423
+ "llmTip": "Message.body (contentType 'html' for HTML) replaces the whole draft body, dropping the quoted history; 'comment' keeps it. Specifying both 'comment' and Message.body returns 400. Signatures are added by the Outlook client only, not via Graph.",
424
+ "mcpApp": {
425
+ "view": "mail-draft",
426
+ "tools": { "get": "get-mail-message", "send": "send-draft-message" }
427
+ }
400
428
  },
401
429
  {
402
430
  "pathPattern": "/me/messages/{message-id}/createReplyAll",
@@ -404,7 +432,11 @@
404
432
  "toolName": "create-reply-all-draft",
405
433
  "presets": ["mail", "outlook", "personal"],
406
434
  "scopes": ["Mail.ReadWrite"],
407
- "llmTip": "Message.body (contentType 'html' for HTML) replaces the whole draft body, dropping the quoted history; 'comment' keeps it. Specifying both 'comment' and Message.body returns 400. Signatures are added by the Outlook client only, not via Graph."
435
+ "llmTip": "Message.body (contentType 'html' for HTML) replaces the whole draft body, dropping the quoted history; 'comment' keeps it. Specifying both 'comment' and Message.body returns 400. Signatures are added by the Outlook client only, not via Graph.",
436
+ "mcpApp": {
437
+ "view": "mail-draft",
438
+ "tools": { "get": "get-mail-message", "send": "send-draft-message" }
439
+ }
408
440
  },
409
441
  {
410
442
  "pathPattern": "/me/messages/{message-id}/send",
@@ -756,7 +788,8 @@
756
788
  "toolName": "list-folder-files",
757
789
  "presets": ["files", "onedrive", "personal"],
758
790
  "scopes": [["Files.Read"], ["Sites.Selected"]],
759
- "appScopes": [["Files.Read.All"], ["Sites.Read.All"], ["Sites.Selected"]]
791
+ "appScopes": [["Files.Read.All"], ["Sites.Read.All"], ["Sites.Selected"]],
792
+ "mcpApp": { "view": "file-browser" }
760
793
  },
761
794
  {
762
795
  "pathPattern": "/drives/{drive-id}/items/{driveItem-id}",
@@ -93,6 +93,12 @@ import {
93
93
  userFieldEnforcement
94
94
  } from "./lib/user-field-policy.js";
95
95
  import logger from "./logger.js";
96
+ import {
97
+ mcpAppResultWithoutBody,
98
+ mcpAppToolMeta,
99
+ noteMcpAppTool,
100
+ registerMcpAppViews
101
+ } from "./mcp-apps.js";
96
102
  import {
97
103
  describeError,
98
104
  describeShape,
@@ -2691,6 +2697,8 @@ function registerGraphToolWithMcp(server, tool, endpointConfig, graphClient, opt
2691
2697
  budget.definitionBudget ?? Number.POSITIVE_INFINITY,
2692
2698
  `${budget.schemaFingerprint}|${tool.alias}`
2693
2699
  ) : void 0;
2700
+ const appBinding = options.mcpApps ? endpointConfig?.mcpApp : void 0;
2701
+ const appMeta = appBinding ? mcpAppToolMeta(appBinding, tool.alias) : void 0;
2694
2702
  server.registerTool(
2695
2703
  tool.alias,
2696
2704
  {
@@ -2703,10 +2711,27 @@ function registerGraphToolWithMcp(server, tool, endpointConfig, graphClient, opt
2703
2711
  destructiveHint: destructive,
2704
2712
  openWorldHint: true
2705
2713
  // All tools call Microsoft Graph API
2706
- }
2714
+ },
2715
+ ...appMeta ? { _meta: appMeta } : {}
2707
2716
  },
2708
- async (params) => executeGraphTool(tool, endpointConfig, graphClient, params, authManager, userFields)
2717
+ async (params) => {
2718
+ if (appMeta && params.excludeResponse === true) {
2719
+ const viewParams = { ...params, excludeResponse: false };
2720
+ return mcpAppResultWithoutBody(
2721
+ await executeGraphTool(
2722
+ tool,
2723
+ endpointConfig,
2724
+ graphClient,
2725
+ viewParams,
2726
+ authManager,
2727
+ userFields
2728
+ )
2729
+ );
2730
+ }
2731
+ return executeGraphTool(tool, endpointConfig, graphClient, params, authManager, userFields);
2732
+ }
2709
2733
  );
2734
+ if (options.mcpApps) noteMcpAppTool(server, tool.alias, appMeta ? appBinding : void 0);
2710
2735
  return fit;
2711
2736
  }
2712
2737
  function registerGraphTools(server, graphClient, options = {}) {
@@ -2856,6 +2881,7 @@ function registerGraphTools(server, graphClient, options = {}) {
2856
2881
  logger.info(
2857
2882
  `Tool registration complete: ${registeredCount} registered, ${skippedCount} skipped, ${failedCount} failed`
2858
2883
  );
2884
+ if (options.mcpApps) registerMcpAppViews(server);
2859
2885
  installDeniedToolAuditHandler(server, deniedTools);
2860
2886
  return registeredCount;
2861
2887
  }
@@ -3078,6 +3104,7 @@ function registerDiscoveryTools(server, graphClient, options = {}) {
3078
3104
  logger.error(`Failed to register eager tool ${name}: ${error.message}`);
3079
3105
  }
3080
3106
  }
3107
+ if (options.mcpApps) registerMcpAppViews(server);
3081
3108
  const searchIndex = buildDiscoverySearchIndex(toolsRegistry, utilityTools);
3082
3109
  const totalCount = toolsRegistry.size + utilityTools.length;
3083
3110
  logger.info(
@@ -0,0 +1,125 @@
1
+ import { readFileSync } from "fs";
2
+ import path from "path";
3
+ import { fileURLToPath } from "url";
4
+ import logger from "./logger.js";
5
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
6
+ const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";
7
+ const CONFIG_PLACEHOLDER = "__MCP_APP_CONFIG__";
8
+ const BRIDGE_PLACEHOLDER = "__MCP_APP_BRIDGE__";
9
+ const SCRIPT_PLACEHOLDER = "__MCP_APP_SCRIPT__";
10
+ const RESOURCE_UI_META = { csp: {}, prefersBorder: true };
11
+ function mcpAppUri(view, toolName) {
12
+ return `ui://ms365/${view}/${toolName}.html`;
13
+ }
14
+ function mcpAppPath(file) {
15
+ return path.join(__dirname, "apps", file);
16
+ }
17
+ const pages = /* @__PURE__ */ new Map();
18
+ function loadPage(view) {
19
+ let page = pages.get(view);
20
+ if (page === void 0) {
21
+ try {
22
+ page = fill(
23
+ readFileSync(mcpAppPath(`${view}.html`), "utf8"),
24
+ BRIDGE_PLACEHOLDER,
25
+ script("bridge.js")
26
+ );
27
+ page = fill(page, SCRIPT_PLACEHOLDER, script(`${view}.js`));
28
+ if (!page.includes(CONFIG_PLACEHOLDER)) {
29
+ throw new Error(`${view}.html has no ${CONFIG_PLACEHOLDER}`);
30
+ }
31
+ } catch (error) {
32
+ page = error;
33
+ }
34
+ if (page instanceof Error) logger.error(`MCP app ${view} left out: ${page.message}`);
35
+ pages.set(view, page);
36
+ }
37
+ return page;
38
+ }
39
+ function script(file) {
40
+ return checkMcpAppScript(file, readFileSync(mcpAppPath(file), "utf8"));
41
+ }
42
+ function checkMcpAppScript(file, source) {
43
+ if (/<\/script/i.test(source)) throw new Error(`${file} contains </script`);
44
+ if (source.includes("<!--")) throw new Error(`${file} contains <!--`);
45
+ if (source.includes("__MCP_APP_")) throw new Error(`${file} contains a placeholder`);
46
+ return source;
47
+ }
48
+ function fill(page, placeholder, content) {
49
+ if (!page.includes(placeholder)) throw new Error(`the page has no ${placeholder}`);
50
+ return page.replace(placeholder, () => content);
51
+ }
52
+ const servers = /* @__PURE__ */ new WeakMap();
53
+ function mcpAppToolMeta(binding, toolName) {
54
+ if (loadPage(binding.view) instanceof Error) return void 0;
55
+ const uri = mcpAppUri(binding.view, toolName);
56
+ return { ui: { resourceUri: uri }, "ui/resourceUri": uri };
57
+ }
58
+ function mcpAppResultWithoutBody(result) {
59
+ if (result.isError) return result;
60
+ const block = result.content.find((item) => item.type === "text");
61
+ let body;
62
+ try {
63
+ body = block?.type === "text" ? JSON.parse(block.text) : void 0;
64
+ } catch {
65
+ body = void 0;
66
+ }
67
+ return {
68
+ ...result,
69
+ content: [{ type: "text", text: JSON.stringify({ success: true }) }],
70
+ ...body && typeof body === "object" && !Array.isArray(body) ? { structuredContent: body } : {}
71
+ };
72
+ }
73
+ function noteMcpAppTool(server, toolName, binding) {
74
+ let apps = servers.get(server);
75
+ if (!apps) {
76
+ apps = { tools: /* @__PURE__ */ new Set(), bindings: [] };
77
+ servers.set(server, apps);
78
+ }
79
+ apps.tools.add(toolName);
80
+ if (binding) apps.bindings.push({ toolName, binding });
81
+ }
82
+ function registerMcpAppViews(server) {
83
+ const apps = servers.get(server);
84
+ if (!apps) return;
85
+ servers.delete(server);
86
+ for (const { toolName, binding } of apps.bindings) {
87
+ const page = loadPage(binding.view);
88
+ if (page instanceof Error) continue;
89
+ const tools = {};
90
+ for (const [role, name] of Object.entries(binding.tools ?? {})) {
91
+ if (apps.tools.has(name)) tools[role] = name;
92
+ }
93
+ const config = JSON.stringify({ toolName, tools }).replace(/</g, "\\u003c");
94
+ const html = page.replace(CONFIG_PLACEHOLDER, () => config);
95
+ const uri = mcpAppUri(binding.view, toolName);
96
+ try {
97
+ server.registerResource(
98
+ `${binding.view}:${toolName}`,
99
+ uri,
100
+ {
101
+ description: `MCP Apps view for ${toolName}`,
102
+ mimeType: MCP_APP_MIME_TYPE,
103
+ _meta: { ui: RESOURCE_UI_META }
104
+ },
105
+ async () => ({
106
+ contents: [
107
+ { uri, mimeType: MCP_APP_MIME_TYPE, text: html, _meta: { ui: RESOURCE_UI_META } }
108
+ ]
109
+ })
110
+ );
111
+ } catch (error) {
112
+ logger.error(`MCP app view for ${toolName} left out: ${error.message}`);
113
+ }
114
+ }
115
+ }
116
+ export {
117
+ MCP_APP_MIME_TYPE,
118
+ checkMcpAppScript,
119
+ mcpAppPath,
120
+ mcpAppResultWithoutBody,
121
+ mcpAppToolMeta,
122
+ mcpAppUri,
123
+ noteMcpAppTool,
124
+ registerMcpAppViews
125
+ };