@softeria/ms-365-mcp-server 0.181.2 → 0.182.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/PRESETS.md CHANGED
@@ -14,9 +14,9 @@ Every preset also includes the account tools (`login`, `logout`, `verify-login`,
14
14
  | `calendar` | [full](#calendar-full)<br>[read only](#calendar-read-only) | 47<br>22 | 7<br>5 | -<br>- | Calendar and event management |
15
15
  | `contacts` | [full](#contacts-full)<br>[read only](#contacts-read-only) | 15<br>7 | 1<br>1 | -<br>- | Outlook contacts management |
16
16
  | `excel` | [full](#excel-full)<br>[read only](#excel-read-only) | 25<br>9 | 1<br>1 | -<br>- | Excel spreadsheet operations |
17
- | `files` | [full](#files-full)<br>[read only](#files-read-only) | 25<br>14 | 3<br>2 | -<br>- | OneDrive file and folder operations |
17
+ | `files` | [full](#files-full)<br>[read only](#files-read-only) | 26<br>14 | 3<br>2 | -<br>- | OneDrive file and folder operations |
18
18
  | `mail` | [full](#mail-full)<br>[read only](#mail-read-only) | 50<br>19 | 5<br>3 | -<br>- | Email operations (read, send, manage folders, attachments) |
19
- | `onedrive` | [full](#onedrive-full)<br>[read only](#onedrive-read-only) | 23<br>12 | 2<br>1 | -<br>- | OneDrive app only: drive and file operations, excluding Excel |
19
+ | `onedrive` | [full](#onedrive-full)<br>[read only](#onedrive-read-only) | 24<br>12 | 2<br>1 | -<br>- | OneDrive app only: drive and file operations, excluding Excel |
20
20
  | `onenote` | [full](#onenote-full)<br>[read only](#onenote-read-only) | 29<br>17 | 5<br>2 | -<br>- | OneNote notebook operations |
21
21
  | `outlook` | [full](#outlook-full)<br>[read only](#outlook-read-only) | 97<br>37 | 8<br>6 | -<br>- | Outlook app only: mail, calendar and contacts |
22
22
  | `personal` | [full](#personal-full)<br>[read only](#personal-read-only) | 178<br>74 | 20<br>15 | -<br>- | Personal productivity tools (mail, calendar, files, contacts, tasks, notes, search) |
@@ -905,7 +905,7 @@ Scopes (1):
905
905
 
906
906
  OneDrive file and folder operations
907
907
 
908
- Tools (25):
908
+ Tools (26):
909
909
 
910
910
  - `copy-drive-item`
911
911
  - `create-drive-item-preview`
@@ -922,6 +922,7 @@ Tools (25):
922
922
  - `get-drive-item`
923
923
  - `get-drive-root-item`
924
924
  - `get-sensitivity-label`
925
+ - `get-upload-url`
925
926
  - `list-drive-item-permissions`
926
927
  - `list-drive-item-thumbnails`
927
928
  - `list-drive-item-versions`
@@ -1066,7 +1067,7 @@ Scopes (3):
1066
1067
 
1067
1068
  OneDrive app only: drive and file operations, excluding Excel
1068
1069
 
1069
- Tools (23):
1070
+ Tools (24):
1070
1071
 
1071
1072
  - `copy-drive-item`
1072
1073
  - `create-drive-item-preview`
@@ -1082,6 +1083,7 @@ Tools (23):
1082
1083
  - `get-drive-delta`
1083
1084
  - `get-drive-item`
1084
1085
  - `get-drive-root-item`
1086
+ - `get-upload-url`
1085
1087
  - `list-drive-item-permissions`
1086
1088
  - `list-drive-item-thumbnails`
1087
1089
  - `list-drive-item-versions`
package/README.md CHANGED
@@ -949,7 +949,10 @@ JSON overhead; this is character arithmetic, not a tokenizer-specific measuremen
949
949
  `--enable-attachment-urls` (HTTP mode, off by default) closes that gap. When Graph has no
950
950
  URL of its own, `get-download-url` mints one this server serves. With it on,
951
951
  `get-download-url` is registered under every `--preset` (except the send-only `teams-write`),
952
- so a `--preset mail` agent that lists an attachment can mint a URL for it. A minted URL only
952
+ so a `--preset mail` agent that lists an attachment can mint a URL for it. OneDrive and
953
+ SharePoint files get a minted URL too, instead of Graph's own: that one is about 1,300
954
+ characters, too long for an agent that has to type it into a command, such as `curl` in a
955
+ sandbox that cannot see tool results. A minted URL only
953
956
  works if the preset's scopes cover the resource: a contacts, tasks or excel preset has no Mail
954
957
  scopes, so a URL minted for a mail attachment fails when fetched.
955
958
 
@@ -1017,7 +1020,16 @@ Content-Length: <file size>
1017
1020
  `/me/events/{id}/attachments` for an event); `name` and `contentType` are recorded on the
1018
1021
  attachment. Files under 3 MB are attached inline; larger ones, up to Graph's 150 MB, stream
1019
1022
  through an upload session in 3.75 MiB chunks, so the server never holds more than one chunk.
1020
- `Content-Length` is required. The ticket is single-use and burnt on first presentation
1023
+ `Content-Length` is required.
1024
+
1025
+ `target` can also be a OneDrive or SharePoint folder (`/me/drive/root`,
1026
+ `/me/drive/items/{folder-id}`, `/drives/{drive-id}/items/{folder-id}`,
1027
+ `/sites/{site-id}/drive/items/{folder-id}`); the file is then created there as `name`,
1028
+ always through a Graph upload session, with the same 150 MB cap. `conflictBehavior` decides
1029
+ what happens when the name is taken: `fail` (the default, answered with 409), `replace` or
1030
+ `rename`. `contentType` and `contentId` do not apply to drive files.
1031
+
1032
+ The ticket is single-use and burnt on first presentation
1021
1033
  whatever the outcome, and the upload is attached as the identity that minted it, exactly as
1022
1034
  downloads are fetched. An upload ticket presented to `GET` (or a download ticket to `PUT`)
1023
1035
  is refused with the same 404 as any other bad ticket.
@@ -1392,6 +1404,9 @@ If you're having problems or need help:
1392
1404
  - Email: eirikb@eirikb.no
1393
1405
  - Discord: https://discord.gg/WvGVNScrAZ or @eirikb
1394
1406
 
1407
+ Want to talk about rolling it out in your organization? Connect with me on
1408
+ [LinkedIn](https://www.linkedin.com/in/eirik-brandtz%C3%A6g-22253a286/).
1409
+
1395
1410
  ## License
1396
1411
 
1397
1412
  MIT © 2026 Softeria
@@ -34,7 +34,8 @@ export function createAndSaveSimplifiedOpenAPI(
34
34
  // synthesize the whole operation from endpoints.json.
35
35
  // 2. The method exists but the endpoint declares its own requestBodySchema
36
36
  // (Microsoft published a deprecated/malformed/private-preview body our generator
37
- // can't consume): override ONLY the request body and keep Microsoft's published
37
+ // can't consume, or a body far bigger than what the operation accepts, #757):
38
+ // override ONLY the request body and keep Microsoft's published
38
39
  // responses/parameters intact, so we don't silently drop upstream fields or mask
39
40
  // a future upstream fix. requestBodySchema is explicit opt-in per endpoint.
40
41
  for (const endpoint of endpoints) {
@@ -5,7 +5,12 @@ import {
5
5
  isPlainGraphPath,
6
6
  TICKET_PARAM
7
7
  } from "./lib/attachment-tickets.js";
8
- import { MAX_UPLOAD_BYTES, uploadAttachment } from "./lib/attachment-upload.js";
8
+ import {
9
+ DriveNameConflictError,
10
+ MAX_UPLOAD_BYTES,
11
+ uploadAttachment,
12
+ uploadToDrive
13
+ } from "./lib/attachment-upload.js";
9
14
  const NOT_FOUND_BODY = "Not found";
10
15
  function forceAttachment(header) {
11
16
  if (!header) return "attachment";
@@ -180,6 +185,33 @@ function createAttachmentUploadHandler(deps) {
180
185
  }
181
186
  res.setHeader("cache-control", "no-store");
182
187
  res.setHeader("x-content-type-options", "nosniff");
188
+ if (ticket.drive) {
189
+ try {
190
+ const item = await uploadToDrive(
191
+ graphClient,
192
+ {
193
+ target: ticket.target,
194
+ name: ticket.name,
195
+ size: declared,
196
+ conflictBehavior: ticket.drive.conflictBehavior,
197
+ accessToken
198
+ },
199
+ req
200
+ );
201
+ res.status(201).json({ ok: true, name: ticket.name, size: declared, ...item });
202
+ } catch (error) {
203
+ logger.error(`Drive upload failed for ${ticket.target}: ${error.message}`);
204
+ if (res.headersSent) return;
205
+ if (error instanceof DriveNameConflictError) {
206
+ res.status(409).type("text/plain").send(
207
+ "A file with that name already exists in the folder. Mint a new URL with conflictBehavior replace or rename."
208
+ );
209
+ return;
210
+ }
211
+ res.status(502).type("text/plain").send("Upstream upload failed");
212
+ }
213
+ return;
214
+ }
183
215
  try {
184
216
  const created = await uploadAttachment(
185
217
  graphClient,
package/dist/cli.js CHANGED
@@ -31,7 +31,7 @@ program.name("ms-365-mcp-server").description("Microsoft 365 MCP Server").versio
31
31
  "Enable login/logout tools when using HTTP mode (disabled by default in HTTP mode)"
32
32
  ).option(
33
33
  "--enable-attachment-urls",
34
- "HTTP mode only. Let get-download-url mint a short-TTL, single-use URL served by this server for Graph byte resources that expose no pre-authenticated URL of their own (mail and event attachments, meeting recordings, other $value endpoints). Also adds get-download-url to any --preset that lacks it (except teams-write). Requires MS365_MCP_ATTACHMENT_URL_BASE; MS365_MCP_ATTACHMENT_URL_KEY (or _KEY_FILE) is optional and adds an HMAC signature for fetchers that verify one"
34
+ "HTTP mode only. Let get-download-url mint a short-TTL, single-use URL served by this server for Graph byte resources that expose no pre-authenticated URL of their own (mail and event attachments, meeting recordings, other $value endpoints), and a short one for OneDrive/SharePoint files too; get-upload-url then also takes drive folders. Also adds get-download-url to any --preset that lacks it (except teams-write). Requires MS365_MCP_ATTACHMENT_URL_BASE; MS365_MCP_ATTACHMENT_URL_KEY (or _KEY_FILE) is optional and adds an HMAC signature for fetchers that verify one"
35
35
  ).option(
36
36
  "--attachment-port <port>",
37
37
  "HTTP mode only. Serve the attachment download route on its own listener on this port instead of on the MCP app, so a caller that can fetch attachments cannot also reach /mcp. Requires --enable-attachment-urls, and MS365_MCP_ATTACHMENT_URL_BASE must name this port. A separate port only isolates the two surfaces if they also bind separate interfaces \u2014 see --attachment-host. Equivalent env var: MS365_MCP_ATTACHMENT_PORT."
@@ -2982,7 +2982,60 @@
2982
2982
  "presets": ["teams", "work"],
2983
2983
  "workScopes": ["Chat.Create", "Chat.ReadWrite"],
2984
2984
  "appScopes": ["Chat.Create"],
2985
- "llmTip": "Creates a new 1:1 or group Teams chat. Body: { chatType ('oneOnOne' or 'group'), topic (optional, group only), members: [{ '@odata.type': '#microsoft.graph.aadUserConversationMember', roles: ['owner' | 'guest'], 'user@odata.bind': 'https://graph.microsoft.com/v1.0/users({id})' }] }. A oneOnOne chat requires exactly 2 members (self + other), both with role 'owner'. For group chats, include all participants. The signed-in user must be one of the members. Returns the created chat with its id — use that id with send-chat-message, list-chat-members, etc."
2985
+ "requestBodySchema": {
2986
+ "type": "object",
2987
+ "required": ["chatType", "members"],
2988
+ "properties": {
2989
+ "chatType": {
2990
+ "type": "string",
2991
+ "enum": ["oneOnOne", "group"]
2992
+ },
2993
+ "topic": {
2994
+ "type": "string",
2995
+ "description": "Chat title. Group chats only."
2996
+ },
2997
+ "members": {
2998
+ "type": "array",
2999
+ "description": "Everyone in the chat, including the signed-in user. Each member also needs '@odata.type': '#microsoft.graph.aadUserConversationMember'.",
3000
+ "items": {
3001
+ "type": "object",
3002
+ "required": ["roles", "user@odata.bind"],
3003
+ "properties": {
3004
+ "roles": {
3005
+ "type": "array",
3006
+ "items": { "type": "string", "enum": ["owner", "guest"] }
3007
+ },
3008
+ "user@odata.bind": {
3009
+ "type": "string",
3010
+ "description": "e.g. https://graph.microsoft.com/v1.0/users('{user-id or userPrincipalName}')"
3011
+ },
3012
+ "tenantId": {
3013
+ "type": "string",
3014
+ "description": "Home tenant of a federated user from another organization. Such users keep the 'owner' role."
3015
+ }
3016
+ },
3017
+ "additionalProperties": true
3018
+ }
3019
+ },
3020
+ "installedApps": {
3021
+ "type": "array",
3022
+ "description": "Teams apps to install in the new chat.",
3023
+ "items": {
3024
+ "type": "object",
3025
+ "required": ["teamsApp@odata.bind"],
3026
+ "properties": {
3027
+ "teamsApp@odata.bind": {
3028
+ "type": "string",
3029
+ "description": "e.g. https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{teams-app-id}"
3030
+ }
3031
+ },
3032
+ "additionalProperties": true
3033
+ }
3034
+ }
3035
+ },
3036
+ "additionalProperties": true
3037
+ },
3038
+ "llmTip": "A oneOnOne chat takes exactly 2 members. The signed-in user must be a member. In-tenant guests take the 'guest' role. Use the returned id with send-chat-message."
2986
3039
  },
2987
3040
  {
2988
3041
  "pathPattern": "/subscriptions",
@@ -5486,7 +5486,30 @@ const endpoints = makeApi([
5486
5486
  name: "body",
5487
5487
  description: `New entity`,
5488
5488
  type: "Body",
5489
- schema: microsoft_graph_chat
5489
+ schema: z.object({
5490
+ chatType: z.enum(["oneOnOne", "group"]),
5491
+ topic: z.string().describe("Chat title. Group chats only.").optional(),
5492
+ members: z.array(
5493
+ z.object({
5494
+ roles: z.array(z.enum(["owner", "guest"])),
5495
+ "user@odata.bind": z.string().describe(
5496
+ "e.g. https://graph.microsoft.com/v1.0/users('{user-id or userPrincipalName}')"
5497
+ ),
5498
+ tenantId: z.string().describe(
5499
+ "Home tenant of a federated user from another organization. Such users keep the 'owner' role."
5500
+ ).optional()
5501
+ }).loose().loose()
5502
+ ).describe(
5503
+ "Everyone in the chat, including the signed-in user. Each member also needs '@odata.type': '#microsoft.graph.aadUserConversationMember'."
5504
+ ),
5505
+ installedApps: z.array(
5506
+ z.object({
5507
+ "teamsApp@odata.bind": z.string().describe(
5508
+ "e.g. https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{teams-app-id}"
5509
+ )
5510
+ }).loose().loose()
5511
+ ).describe("Teams apps to install in the new chat.").optional()
5512
+ }).loose().loose()
5490
5513
  }
5491
5514
  ],
5492
5515
  response: z.void()
@@ -725,6 +725,10 @@ const contentIdSchema = z.string().optional().describe(
725
725
  'Attach inline under this Content-ID instead of as a regular attachment, so the HTML body can show the file with <img src="cid:<contentId>">, e.g. a picture in an email signature. Letters, digits, ".", "_", "@", "-".'
726
726
  );
727
727
  const UPLOAD_TARGET_ERROR = "target must be the attachments collection of a draft message or an event: /me/messages/{message-id}/attachments or /me/events/{event-id}/attachments (or /users/{user-id}/... for another mailbox).";
728
+ const DRIVE_UPLOAD_TARGET = /^(?:\/drives\/[^/]+|\/(?:me|users\/[^/]+|groups\/[^/]+|sites\/[^/]+)\/drive|\/(?:groups|sites)\/[^/]+\/drives\/[^/]+)\/(?:root|items\/[^/]+)$/;
729
+ const UPLOAD_ANY_TARGET_ERROR = `${UPLOAD_TARGET_ERROR} Or a OneDrive/SharePoint folder: /me/drive/root, /me/drive/items/{folder-id}, /drives/{drive-id}/items/{folder-id} or /sites/{site-id}/drive/items/{folder-id}.`;
730
+ const DRIVE_NAME_FORBIDDEN = /["*:<>?/\\|]/;
731
+ const DRIVE_CONFLICT_BEHAVIORS = ["fail", "replace", "rename"];
728
732
  function uploadError(message) {
729
733
  return { content: [{ type: "text", text: JSON.stringify({ error: message }) }], isError: true };
730
734
  }
@@ -734,19 +738,33 @@ function cleanAttachmentName(name) {
734
738
  return code > 31 && code !== 127;
735
739
  }).join("").slice(0, 255);
736
740
  }
741
+ function isEncodable(value) {
742
+ try {
743
+ encodeURIComponent(value);
744
+ return true;
745
+ } catch {
746
+ return false;
747
+ }
748
+ }
737
749
  function optionalContentId(value) {
738
750
  return typeof value === "string" && value.length > 0 ? value : void 0;
739
751
  }
740
- async function mintUploadUrl(target, name, contentType, accountParam, authManager, contentId) {
752
+ async function mintUploadUrl(target, name, contentType, accountParam, authManager, contentId, conflictBehavior) {
741
753
  const minting = getAttachmentMinting();
754
+ const isDrive = DRIVE_UPLOAD_TARGET.test(target);
742
755
  if (!minting) {
756
+ if (isDrive) {
757
+ return uploadError(
758
+ "This server is not running with --enable-attachment-urls, so no upload URL can be minted. Upload small files with upload-file-content, or get a Graph upload URL with create-upload-session."
759
+ );
760
+ }
743
761
  const smallFileTool = target.includes("/events/") ? "add-calendar-event-attachment" : target.startsWith("/users/") ? "add-shared-mailbox-attachment" : "add-mail-attachment";
744
762
  return uploadError(
745
763
  `This server is not running with --enable-attachment-urls, so no upload URL can be minted. Attach small files with ${smallFileTool} (base64 contentBytes).`
746
764
  );
747
765
  }
748
- if (!UPLOAD_TARGET.test(target) || !isPlainGraphPath(target)) {
749
- return uploadError(UPLOAD_TARGET_ERROR);
766
+ if (!UPLOAD_TARGET.test(target) && !isDrive || !isPlainGraphPath(target)) {
767
+ return uploadError(UPLOAD_ANY_TARGET_ERROR);
750
768
  }
751
769
  const cleanName = cleanAttachmentName(name);
752
770
  if (!cleanName) return uploadError("name is required.");
@@ -756,6 +774,24 @@ async function mintUploadUrl(target, name, contentType, accountParam, authManage
756
774
  if (contentId !== void 0 && !UPLOAD_CONTENT_ID.test(contentId)) {
757
775
  return uploadError(UPLOAD_CONTENT_ID_ERROR);
758
776
  }
777
+ let drive;
778
+ if (isDrive) {
779
+ if (contentId !== void 0) {
780
+ return uploadError("contentId applies only to mail and event attachments, not drive files.");
781
+ }
782
+ if (cleanName !== name || DRIVE_NAME_FORBIDDEN.test(name) || name.endsWith(".") || !isEncodable(name)) {
783
+ return uploadError(
784
+ 'name must be a plain file name: no " * : < > ? / \\ | characters, no leading or trailing spaces, not ending in "." and at most 255 characters, e.g. report.pdf.'
785
+ );
786
+ }
787
+ const behavior = conflictBehavior ?? "fail";
788
+ if (!DRIVE_CONFLICT_BEHAVIORS.includes(behavior)) {
789
+ return uploadError("conflictBehavior must be fail, replace or rename.");
790
+ }
791
+ drive = { conflictBehavior: behavior };
792
+ } else if (conflictBehavior !== void 0) {
793
+ return uploadError("conflictBehavior applies only to OneDrive/SharePoint folder targets.");
794
+ }
759
795
  const identityFromRequest = Boolean(authManager?.isOAuthModeEnabled() || getRequestTokens());
760
796
  const requestToken = identityFromRequest ? getRequestTokens()?.accessToken ?? await authManager?.getToken().catch(() => null) ?? void 0 : void 0;
761
797
  if (identityFromRequest && !requestToken) {
@@ -767,7 +803,12 @@ async function mintUploadUrl(target, name, contentType, accountParam, authManage
767
803
  if (accountModeError) return uploadError(accountModeError);
768
804
  let ticket;
769
805
  try {
770
- const upload = { name: cleanName, contentType, ...contentId ? { contentId } : {} };
806
+ const upload = {
807
+ name: cleanName,
808
+ contentType,
809
+ ...contentId ? { contentId } : {},
810
+ ...drive ? { drive } : {}
811
+ };
771
812
  ticket = requestToken ? minting.store.mintUploadWithToken(target, requestToken, upload) : minting.store.mintUpload(target, accountParam, upload);
772
813
  } catch (error) {
773
814
  if (error instanceof TicketStoreFullError) return uploadError(error.message);
@@ -783,6 +824,7 @@ async function mintUploadUrl(target, name, contentType, accountParam, authManage
783
824
  expiresAt: new Date(ticket.expiresAtMs).toISOString(),
784
825
  singleUse: true,
785
826
  maxBytes: MAX_UPLOAD_BYTES,
827
+ ...drive && { conflictBehavior: drive.conflictBehavior },
786
828
  note: 'PUT the raw file bytes with a Content-Length (e.g. curl -T <file> "<uploadUrl>"). Served by this server; valid for one upload until it expires.'
787
829
  })
788
830
  }
@@ -805,7 +847,7 @@ async function probeAttachment(target, graphClient, accessToken) {
805
847
  return {};
806
848
  }
807
849
  }
808
- async function mintDownloadUrl(target, accountParam, authManager, probeWith) {
850
+ async function mintDownloadUrl(target, accountParam, authManager, probeWith, known) {
809
851
  const minting = getAttachmentMinting();
810
852
  if (!minting) return null;
811
853
  const identityFromRequest = Boolean(authManager?.isOAuthModeEnabled() || getRequestTokens());
@@ -843,7 +885,7 @@ async function mintDownloadUrl(target, accountParam, authManager, probeWith) {
843
885
  isError: true
844
886
  };
845
887
  }
846
- const probe = probeWith ? await probeAttachment(
888
+ const probe = known ? known.probe : probeWith ? await probeAttachment(
847
889
  target,
848
890
  probeWith,
849
891
  requestToken ?? await authManager?.getTokenForAccount(accountParam).catch(() => void 0)
@@ -866,6 +908,7 @@ async function mintDownloadUrl(target, accountParam, authManager, probeWith) {
866
908
  type: "text",
867
909
  text: JSON.stringify({
868
910
  downloadUrl: buildAttachmentUrl(minting.config, ticket.id),
911
+ ...known?.fields,
869
912
  expiresAt: new Date(ticket.expiresAtMs).toISOString(),
870
913
  singleUse: true,
871
914
  note: "Served by this server, not by Microsoft Graph. Valid for one fetch until it expires."
@@ -896,20 +939,25 @@ const UTILITY_TOOLS = [
896
939
  name: "get-upload-url",
897
940
  method: "PUT",
898
941
  path: "tool:get-upload-url",
899
- searchKeywords: "upload attachment attach file draft email attach file event large attachment send file out-of-band upload url",
900
- description: 'Mint a short-lived, single-use URL that this server serves for uploading a file as an attachment to a draft message or an event, so the bytes go straight from the caller to Microsoft Graph instead of passing as base64 through the agent context. target is the attachments collection of the item: /me/messages/{message-id}/attachments (a draft; create it first) or /me/events/{event-id}/attachments. PUT the raw file bytes to the returned uploadUrl with a Content-Length (e.g. curl -T file "<uploadUrl>"); the response confirms the attachment. Files under 3 MB are attached directly, larger ones (up to 150 MB) through a Graph upload session. Pass contentId to attach inline, e.g. a signature picture the HTML body shows with <img src="cid:<contentId>">. Requires --enable-attachment-urls. Returns { uploadUrl, method, expiresAt, singleUse, maxBytes }.',
942
+ searchKeywords: "upload attachment attach file draft email attach file event large attachment send file out-of-band upload url upload onedrive file upload sharepoint file",
943
+ description: 'Mint a short-lived, single-use URL that this server serves for uploading a file as an attachment to a draft message or an event, or as a file in a OneDrive/SharePoint folder, so the bytes go straight from the caller to Microsoft Graph instead of passing as base64 through the agent context. target is the attachments collection of the item: /me/messages/{message-id}/attachments (a draft; create it first) or /me/events/{event-id}/attachments; or a drive folder: /me/drive/root, /me/drive/items/{folder-id}, /drives/{drive-id}/items/{folder-id}, /sites/{site-id}/drive/items/{folder-id}. PUT the raw file bytes to the returned uploadUrl with a Content-Length (e.g. curl -T file "<uploadUrl>"); the response confirms the upload. Up to 150 MB. Pass contentId to attach inline, e.g. a signature picture the HTML body shows with <img src="cid:<contentId>">. For a drive folder, conflictBehavior says what happens when the name is taken (default fail; contentId does not apply). Requires --enable-attachment-urls. Returns { uploadUrl, method, expiresAt, singleUse, maxBytes, conflictBehavior? }.',
901
944
  readOnlyHint: false,
902
945
  openWorldHint: true,
903
946
  buildSchema: (ctx) => {
904
947
  const schema = {
905
948
  target: z.string().describe(
906
- "Attachments collection of a draft message or an event, e.g. /me/messages/{message-id}/attachments, /me/events/{event-id}/attachments, or /users/{user-id}/messages/{message-id}/attachments for another mailbox."
949
+ "Attachments collection of a draft message or an event, e.g. /me/messages/{message-id}/attachments, /me/events/{event-id}/attachments, or /users/{user-id}/messages/{message-id}/attachments for another mailbox. Or a OneDrive/SharePoint folder: /me/drive/root, /me/drive/items/{folder-id}, /drives/{drive-id}/items/{folder-id}, /sites/{site-id}/drive/items/{folder-id}."
950
+ ),
951
+ name: z.string().describe(
952
+ "File name as it will be stored, e.g. report.pdf: the attachment name, or the file name in the drive folder."
907
953
  ),
908
- name: z.string().describe("Attachment file name as the recipient will see it, e.g. report.pdf"),
909
954
  contentType: z.string().optional().describe(
910
955
  "MIME type of the file, e.g. application/pdf. Defaults to application/octet-stream."
911
956
  ),
912
- contentId: contentIdSchema
957
+ contentId: contentIdSchema,
958
+ conflictBehavior: z.enum(DRIVE_CONFLICT_BEHAVIORS).optional().describe(
959
+ "Drive folder targets only: what happens when the folder already has a file with this name. fail (default), replace, or rename."
960
+ )
913
961
  };
914
962
  if (ctx.multiAccount) {
915
963
  schema["account"] = z.string().optional().describe(
@@ -934,7 +982,8 @@ const UTILITY_TOOLS = [
934
982
  contentType,
935
983
  params.account,
936
984
  authManager,
937
- optionalContentId(params.contentId)
985
+ optionalContentId(params.contentId),
986
+ params.conflictBehavior === "" ? void 0 : params.conflictBehavior
938
987
  );
939
988
  }
940
989
  },
@@ -1468,7 +1517,7 @@ const UTILITY_TOOLS = [
1468
1517
  method: "GET",
1469
1518
  path: "tool:get-download-url",
1470
1519
  searchKeywords: "download file download drive file download onedrive file sharepoint file download large drive file large sharepoint file large file out-of-band download pre-authenticated url",
1471
- description: "Resolve a short-lived, pre-authenticated download URL for Microsoft Graph binary content that exposes one (drive/SharePoint file content). The returned URL streams the bytes with NO Authorization header, so the client can fetch it straight to disk (e.g. curl) without round-tripping base64 through the agent context. Prefer this over download-bytes for any file above a few KB or any bulk download. Returns { downloadUrl, name?, size?, contentType? }. Mail file attachments (/messages/{id}/attachments/{id}/$value), meeting recordings and other $value byte endpoints have no pre-authenticated URL from Graph itself, but call this tool for them anyway: a server running with --enable-attachment-urls mints its own single-use URL for them, and one without it answers with the reason and points at download-bytes.",
1520
+ description: "Resolve a short-lived, pre-authenticated download URL for Microsoft Graph binary content that exposes one (drive/SharePoint file content). The returned URL streams the bytes with NO Authorization header, so the client can fetch it straight to disk (e.g. curl) without round-tripping base64 through the agent context. Prefer this over download-bytes for any file above a few KB or any bulk download. Returns { downloadUrl, name?, size?, contentType? }. Mail file attachments (/messages/{id}/attachments/{id}/$value), meeting recordings and other $value byte endpoints have no pre-authenticated URL from Graph itself, but call this tool for them anyway: a server running with --enable-attachment-urls mints its own single-use URL for them, and one without it answers with the reason and points at download-bytes. With --enable-attachment-urls, drive files get a short single-use URL from this server as well, instead of the long one from Graph.",
1472
1521
  readOnlyHint: true,
1473
1522
  openWorldHint: true,
1474
1523
  buildSchema: (ctx) => {
@@ -1659,6 +1708,34 @@ const UTILITY_TOOLS = [
1659
1708
  }
1660
1709
  }
1661
1710
  const downloadUrl = item?.["@microsoft.graph.downloadUrl"];
1711
+ const file = item?.file;
1712
+ if (getAttachmentMinting() && item && !item.folder) {
1713
+ const name = typeof item.name === "string" ? item.name : void 0;
1714
+ const mimeType = typeof file?.mimeType === "string" ? file.mimeType : void 0;
1715
+ const driveId = item.parentReference?.driveId;
1716
+ const byId = typeof driveId === "string" && typeof item.id === "string" ? `/drives/${encodeURIComponent(driveId)}/items/${encodeURIComponent(item.id)}/content` : `${itemPath}/content`;
1717
+ const minted = await mintDownloadUrl(byId, accountParam, authManager, void 0, {
1718
+ probe: {
1719
+ ...name && { probedName: name },
1720
+ ...mimeType && { probedContentType: mimeType }
1721
+ },
1722
+ fields: { name, size: item.size, contentType: mimeType }
1723
+ });
1724
+ if (minted) return minted;
1725
+ }
1726
+ if (getAttachmentMinting() && item?.folder) {
1727
+ return {
1728
+ content: [
1729
+ {
1730
+ type: "text",
1731
+ text: JSON.stringify({
1732
+ error: "target is a folder. get-download-url serves one file; list the folder and ask for each file."
1733
+ })
1734
+ }
1735
+ ],
1736
+ isError: true
1737
+ };
1738
+ }
1662
1739
  if (!downloadUrl) {
1663
1740
  const minted = await mintDownloadUrl(`${itemPath}/content`, accountParam, authManager);
1664
1741
  if (minted) return minted;
@@ -1675,7 +1752,6 @@ const UTILITY_TOOLS = [
1675
1752
  _meta: response._meta
1676
1753
  };
1677
1754
  }
1678
- const file = item?.file;
1679
1755
  return {
1680
1756
  content: [
1681
1757
  {
@@ -1,6 +1,14 @@
1
1
  const MAX_UPLOAD_BYTES = 150 * 1024 * 1024;
2
2
  const INLINE_UPLOAD_LIMIT = 3 * 1024 * 1024;
3
3
  const UPLOAD_CHUNK_BYTES = 320 * 1024 * 12;
4
+ class DriveNameConflictError extends Error {
5
+ }
6
+ class ChunkStatusError extends Error {
7
+ constructor(message, status) {
8
+ super(message);
9
+ this.status = status;
10
+ }
11
+ }
4
12
  async function putChunk(uploadUrl, chunk, start, total) {
5
13
  const end = start + chunk.length - 1;
6
14
  const response = await fetch(uploadUrl, {
@@ -15,8 +23,40 @@ async function putChunk(uploadUrl, chunk, start, total) {
15
23
  body: chunk.buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength)
16
24
  });
17
25
  if (![200, 201, 202].includes(response.status)) {
18
- throw new Error(`Upload session chunk ${start}-${end} answered HTTP ${response.status}`);
26
+ throw new ChunkStatusError(
27
+ `Upload session chunk ${start}-${end} answered HTTP ${response.status}`,
28
+ response.status
29
+ );
30
+ }
31
+ return response;
32
+ }
33
+ async function streamToSession(uploadUrl, size, source) {
34
+ let pending = [];
35
+ let pendingBytes = 0;
36
+ let offset = 0;
37
+ let last;
38
+ for await (const piece of source) {
39
+ pending.push(piece);
40
+ pendingBytes += piece.length;
41
+ if (offset + pendingBytes > size) {
42
+ throw new Error(`Source is longer than the declared ${size} bytes`);
43
+ }
44
+ while (pendingBytes >= UPLOAD_CHUNK_BYTES) {
45
+ const joined = Buffer.concat(pending);
46
+ const chunk = joined.subarray(0, UPLOAD_CHUNK_BYTES);
47
+ last = await putChunk(uploadUrl, chunk, offset, size);
48
+ offset += chunk.length;
49
+ const rest = joined.subarray(UPLOAD_CHUNK_BYTES);
50
+ pending = rest.length ? [Buffer.from(rest)] : [];
51
+ pendingBytes = rest.length;
52
+ }
53
+ }
54
+ if (pendingBytes > 0) {
55
+ last = await putChunk(uploadUrl, Buffer.concat(pending), offset, size);
56
+ offset += pendingBytes;
19
57
  }
58
+ if (offset !== size) throw new Error(`Source ended before the declared ${size} bytes`);
59
+ return last;
20
60
  }
21
61
  async function uploadAttachment(graphClient, upload, source) {
22
62
  const { target, name, contentType, size, accessToken, contentId } = upload;
@@ -51,33 +91,56 @@ async function uploadAttachment(graphClient, upload, source) {
51
91
  })
52
92
  });
53
93
  if (!session?.uploadUrl) throw new Error("Upload session returned no uploadUrl");
54
- let pending = [];
55
- let pendingBytes = 0;
56
- let offset = 0;
57
- for await (const piece of source) {
58
- pending.push(piece);
59
- pendingBytes += piece.length;
60
- if (offset + pendingBytes > size) {
61
- throw new Error(`Source is longer than the declared ${size} bytes`);
62
- }
63
- while (pendingBytes >= UPLOAD_CHUNK_BYTES) {
64
- const joined = Buffer.concat(pending);
65
- const chunk = joined.subarray(0, UPLOAD_CHUNK_BYTES);
66
- await putChunk(session.uploadUrl, chunk, offset, size);
67
- offset += chunk.length;
68
- const rest = joined.subarray(UPLOAD_CHUNK_BYTES);
69
- pending = rest.length ? [Buffer.from(rest)] : [];
70
- pendingBytes = rest.length;
94
+ await streamToSession(session.uploadUrl, size, source);
95
+ return {};
96
+ }
97
+ async function uploadToDrive(graphClient, upload, source) {
98
+ const { target, name, size, conflictBehavior, accessToken } = upload;
99
+ let session;
100
+ try {
101
+ session = await graphClient.makeRequest(
102
+ `${target}:/${encodeURIComponent(name)}:/createUploadSession`,
103
+ {
104
+ method: "POST",
105
+ accessToken,
106
+ body: JSON.stringify({
107
+ item: { "@microsoft.graph.conflictBehavior": conflictBehavior, name }
108
+ })
109
+ }
110
+ );
111
+ } catch (error) {
112
+ if (error.httpStatus === 409) {
113
+ throw new DriveNameConflictError(error.message);
71
114
  }
115
+ throw error;
72
116
  }
73
- if (pendingBytes > 0) {
74
- await putChunk(session.uploadUrl, Buffer.concat(pending), offset, size);
75
- offset += pendingBytes;
117
+ if (!session?.uploadUrl) throw new Error("Upload session returned no uploadUrl");
118
+ const uploadUrl = session.uploadUrl;
119
+ let item;
120
+ try {
121
+ const last = await streamToSession(uploadUrl, size, source);
122
+ if (!last || last.status !== 200 && last.status !== 201) {
123
+ throw new Error(`Upload session did not complete (HTTP ${last?.status ?? "none"})`);
124
+ }
125
+ item = await last.json().catch(() => void 0);
126
+ if (typeof item?.id !== "string") throw new Error("Upload session returned no driveItem");
127
+ } catch (error) {
128
+ await fetch(uploadUrl, { method: "DELETE" }).catch(() => void 0);
129
+ if (error instanceof ChunkStatusError && error.status === 409) {
130
+ throw new DriveNameConflictError(error.message);
131
+ }
132
+ throw error;
76
133
  }
77
- if (offset !== size) throw new Error(`Source ended before the declared ${size} bytes`);
78
- return {};
134
+ return {
135
+ ...typeof item?.id === "string" && { id: item.id },
136
+ ...typeof item?.name === "string" && { name: item.name },
137
+ ...typeof item?.size === "number" && { size: item.size },
138
+ ...typeof item?.webUrl === "string" && { webUrl: item.webUrl }
139
+ };
79
140
  }
80
141
  export {
142
+ DriveNameConflictError,
81
143
  MAX_UPLOAD_BYTES,
82
- uploadAttachment
144
+ uploadAttachment,
145
+ uploadToDrive
83
146
  };
@@ -7,7 +7,7 @@ function buildGeneralMcpInstructions(opts) {
7
7
  "Directory $search on collections such as /users or /groups requires ConsistencyLevel: eventual when the tool exposes that header.",
8
8
  "Teams chat and channel messages: prefer HTML contentType in the body; plain text is often mangled by Graph.",
9
9
  "Files / binary content: for large drive/SharePoint file content, prefer get-download-url to resolve a pre-authenticated URL for out-of-band download.",
10
- opts.attachmentUrlsEnabled ? "Attachment URLs are enabled: for document reading and downloads, prefer get-download-url for mail attachments, meeting recordings and other authenticated byte resources, then hand the URL to an external converter or downloader. Use download-bytes only when the caller explicitly needs bytes. Server-minted URLs are single-use: mint a fresh URL for every fetch, including probes, conversion, continuation and retries; retain the same target, account and document selection. Drive-provider URLs may have different lifecycles. This is a preference, not enforcement: enabling attachment URLs does not scrub arbitrary response bodies; use existing tool filtering when a text-only tool surface is required." : "Use download-bytes for authenticated byte reads such as mail attachments, profile photos, Teams hosted content, and meeting recordings.",
10
+ opts.attachmentUrlsEnabled ? "Attachment URLs are enabled: for document reading and downloads, prefer get-download-url for mail attachments, meeting recordings, drive files and other authenticated byte resources, then hand the URL to an external converter or downloader. Use download-bytes only when the caller explicitly needs bytes. Server-minted URLs are single-use: mint a fresh URL for every fetch, including probes, conversion, continuation and retries; retain the same target, account and document selection. This is a preference, not enforcement: enabling attachment URLs does not scrub arbitrary response bodies; use existing tool filtering when a text-only tool surface is required." : "Use download-bytes for authenticated byte reads such as mail attachments, profile photos, Teams hosted content, and meeting recordings.",
11
11
  "In stdio mode (or HTTP with --http-local-file-tools), download-bytes-to-file writes authenticated bytes straight to a local absolute path instead of returning base64. These tools take relative Microsoft Graph paths, not absolute URLs. For uploads, upload-file-content takes a base64 string body (Graph allows 250MB, but the whole string passes through the agent context and a truncated one is written without error); use create-upload-session for anything but small files."
12
12
  ];
13
13
  if (opts.appMode)
@@ -70,7 +70,7 @@ const ACCOUNT_TOOLS = [
70
70
  ];
71
71
  const SCOPED_UTILITY_TOOLS = {
72
72
  "get-download-url": ["files", "onedrive", "personal", "work", "search"],
73
- "get-upload-url": ["mail", "calendar", "outlook", "personal", "work"],
73
+ "get-upload-url": ["mail", "calendar", "outlook", "files", "onedrive", "personal", "work"],
74
74
  "upload-attachment-from-file": ["mail", "calendar", "outlook", "personal", "work"],
75
75
  "parse-teams-url": ["teams", "teams-write", "work"],
76
76
  "read-mail-text": ["mail", "outlook", "personal", "work"]
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@softeria/ms-365-mcp-server",
3
3
  "mcpName": "io.github.Softeria/ms-365-mcp-server",
4
- "version": "0.181.2",
4
+ "version": "0.182.1",
5
5
  "description": " A Model Context Protocol (MCP) server for interacting with Microsoft 365 and Office services through the Graph API",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",
@@ -2982,7 +2982,60 @@
2982
2982
  "presets": ["teams", "work"],
2983
2983
  "workScopes": ["Chat.Create", "Chat.ReadWrite"],
2984
2984
  "appScopes": ["Chat.Create"],
2985
- "llmTip": "Creates a new 1:1 or group Teams chat. Body: { chatType ('oneOnOne' or 'group'), topic (optional, group only), members: [{ '@odata.type': '#microsoft.graph.aadUserConversationMember', roles: ['owner' | 'guest'], 'user@odata.bind': 'https://graph.microsoft.com/v1.0/users({id})' }] }. A oneOnOne chat requires exactly 2 members (self + other), both with role 'owner'. For group chats, include all participants. The signed-in user must be one of the members. Returns the created chat with its id — use that id with send-chat-message, list-chat-members, etc."
2985
+ "requestBodySchema": {
2986
+ "type": "object",
2987
+ "required": ["chatType", "members"],
2988
+ "properties": {
2989
+ "chatType": {
2990
+ "type": "string",
2991
+ "enum": ["oneOnOne", "group"]
2992
+ },
2993
+ "topic": {
2994
+ "type": "string",
2995
+ "description": "Chat title. Group chats only."
2996
+ },
2997
+ "members": {
2998
+ "type": "array",
2999
+ "description": "Everyone in the chat, including the signed-in user. Each member also needs '@odata.type': '#microsoft.graph.aadUserConversationMember'.",
3000
+ "items": {
3001
+ "type": "object",
3002
+ "required": ["roles", "user@odata.bind"],
3003
+ "properties": {
3004
+ "roles": {
3005
+ "type": "array",
3006
+ "items": { "type": "string", "enum": ["owner", "guest"] }
3007
+ },
3008
+ "user@odata.bind": {
3009
+ "type": "string",
3010
+ "description": "e.g. https://graph.microsoft.com/v1.0/users('{user-id or userPrincipalName}')"
3011
+ },
3012
+ "tenantId": {
3013
+ "type": "string",
3014
+ "description": "Home tenant of a federated user from another organization. Such users keep the 'owner' role."
3015
+ }
3016
+ },
3017
+ "additionalProperties": true
3018
+ }
3019
+ },
3020
+ "installedApps": {
3021
+ "type": "array",
3022
+ "description": "Teams apps to install in the new chat.",
3023
+ "items": {
3024
+ "type": "object",
3025
+ "required": ["teamsApp@odata.bind"],
3026
+ "properties": {
3027
+ "teamsApp@odata.bind": {
3028
+ "type": "string",
3029
+ "description": "e.g. https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{teams-app-id}"
3030
+ }
3031
+ },
3032
+ "additionalProperties": true
3033
+ }
3034
+ }
3035
+ },
3036
+ "additionalProperties": true
3037
+ },
3038
+ "llmTip": "A oneOnOne chat takes exactly 2 members. The signed-in user must be a member. In-tenant guests take the 'guest' role. Use the returned id with send-chat-message."
2986
3039
  },
2987
3040
  {
2988
3041
  "pathPattern": "/subscriptions",