Microsoft 365

Jeff Steinbok@jeffsteinbok

πŸšπŸ“§πŸ“…βœ…πŸ“ Microsoft 365 tools for Outlook mail, calendars, Microsoft To Do, and OneDrive through Microsoft Graph.

Tools

onedrive_create_folder
onedrive_delete
onedrive_download
onedrive_list
onedrive_metadata
onedrive_move
onedrive_read
onedrive_search
onedrive_upload
outlook_calendar_fetch
outlook_complete_task
outlook_create_event
outlook_create_task
outlook_delete
outlook_delete_event
outlook_delete_task
outlook_flag
outlook_folders
outlook_forward
outlook_inbox
outlook_label
outlook_mark
outlook_meeting
outlook_move
outlook_query_events
outlook_read
outlook_reply
outlook_save_attachments
outlook_save_draft
outlook_search
outlook_search_store
outlook_send
outlook_task_lists
outlook_tasks
outlook_update_event
outlook_update_task

Readme

🐚 πŸ“§ πŸ“… βœ… πŸ“ Carapace Microsoft 365

npm ClawHub CI Release Publish

Microsoft 365 tools for Outlook mail, calendars, Microsoft To Do, and OneDrive through Microsoft Graph.

The package is named carapace-m365. Outlook and OneDrive tool names remain brand-specific within the Microsoft 365 plugin.

Multiple accounts: one agent per family member

Since 1.5.0, a single install can serve several Microsoft accounts, each mapped to its own OpenClaw agents. A household can give each person their own agent, connected only to that person's Outlook mail, calendar, To Do and OneDrive:

  • Separate accounts: each account has its own sign-in, refresh token, Graph webhook subscription, mail rules and notification channel in the token broker.
  • Strict mapping: an agent mapped to an account uses only that account. Once accounts are mapped, agents that aren't assigned to one are refused.
  • Shared family calendars: these can be shared across agents, with read and write rules for each agent (Calendar access control). Private events on shared calendars are masked.

Setup and an example config are in Multiple broker accounts.

Architecture

The recommended deployment uses the standalone token broker included in this repository:

text
Carapace/OpenClaw M365 plugin ── authenticated /token ──► m365-webhook
                                                     β”œβ”€ owns refresh token
                                                     β”œβ”€ persists rotation
                                                     β”œβ”€ renews Graph subscription
                                                     └─ dispatches inbox notifications

The plugin caches scoped access tokens locally. When a broker is configured it is authoritative: the plugin never falls back to refreshing independently after a broker failure. It may continue only with a cached access token that has not actually expired.

Direct refresh-token mode remains available for migration and simple single-process use.

Quick start

1. Register an app and sign in

In Microsoft Entra ID, create an app registration. Choose personal Microsoft accounts, work/school accounts, or both as the supported account types. Use consumers for personal accounts, your tenant ID for a single work/school tenant, organizations for work/school accounts across tenants, or common for an app that accepts both. Copy the application (client) ID. Under Authentication, enable Allow public client flows. For browser sign-in with PKCE, also add http://localhost under Mobile and desktop applications.

Under API permissions, select Microsoft Graph Delegated permissions for the features you intend to use. For example, add Mail.Read for reading mail. Work/school customers may need an administrator to grant consent. See the app registration guide for the scope mappings.

Clone this repository to run the login script and broker service:

sh
git clone https://github.com/JeffSteinbok/carapace-m365.git
cd carapace-m365
npm run login -- --client-id YOUR_CLIENT_ID --tenant consumers --device-code --token-file ./m365-refresh-token.private

Open Microsoft's verification address shown by the script (microsoft.com/link for personal accounts), enter the displayed code, and sign in to the intended account. Use a new token file for each login. Keep it private and outside version control. For browser sign-in, omit --device-code and retain --token-file. See security notes.

The default grants the core capabilities: calendar-write,mail-write,mail-send,tasks-write. It does not add OneDrive, and OneDrive tools are not registered unless onedrive-read or onedrive-write is explicitly enabled.

powershell
npm run login -- --client-id YOUR_CLIENT_ID --tenant consumers --token-file ./m365-refresh-token.private

Keep the client, tenant, and token-file flags from the command above. The snippets below show feature and scope options:

powershell
# Read-only OneDrive
npm run login -- --features onedrive-read

# Full OneDrive (read and write)
npm run login -- --features onedrive-write

# Existing mail capabilities only
npm run login -- --features mail-write,mail-send

# Calendar only
npm run login -- --features calendar-write

# Existing Outlook capabilities plus full OneDrive
npm run login -- --features calendar-write,mail-write,mail-send,tasks-write,onedrive-write

# Exact delegated scopes are also supported
npm run login -- --scopes "Mail.Read Files.Read"

Run npm run login -- --list-features for every feature name. The login command adds offline_access and openid because interactive authorization needs them to issue a refresh token; Graph access-token requests use only the scopes needed for each operation. After consent it prints M365_FEATURES and a matching plugin features snippet; use that same normalized list in both places.

2. Run the token broker/webhook service

Build everything:

powershell
npm install
npm run build

Set at least:

text
M365_CLIENT_ID=your-app-client-id
M365_TENANT=consumers
M365_REFRESH_TOKEN=the-token-from-login
M365_FEATURES=calendar-write,mail-write,mail-send,tasks-write
M365_TOKEN_BROKER_SECRET=a-long-random-secret
M365_WEBHOOK_URL=https://your-public-host/m365/webhook
M365_WEBHOOK_CLIENT_STATE=another-long-random-secret
NOTIFY_TARGET=your-openclaw-notification-target

Set M365_TENANT to the tenant used during sign-in. Read the value for M365_REFRESH_TOKEN from the private token file into the service environment.

Then start:

powershell
node services/m365-webhook/dist/index.js

The service binds to 127.0.0.1:18790 by default, exposes authenticated POST /token, and accepts Graph notifications at /m365/webhook. See webhook service guide for proxy, state, deployment, and systemd details.

3. Install and configure the plugin

sh
openclaw plugins install clawhub:carapace-m365

For more than one mailbox or identity, see Multiple broker accounts.

json
{
  "plugins": {
    "entries": {
      "m365": {
        "enabled": true,
        "config": {
          "features": ["calendar-write", "mail-write", "mail-send", "tasks-write"],
          "tokenBrokerUrl": "http://127.0.0.1:18790/token",
          "tokenBrokerSecret": "${M365_TOKEN_BROKER_SECRET}"
        }
      }
    }
  }
}

If only tokenBrokerSecret is configured, the URL defaults to http://127.0.0.1:18790/token. Non-loopback broker URLs must use HTTPS.

Direct mode

For migration or a single process without the webhook broker:

json
{
  "plugins": {
    "entries": {
      "m365": {
        "enabled": true,
        "config": {
          "features": ["calendar-write", "mail-write", "mail-send", "tasks-write"],
          "clientId": "${M365_CLIENT_ID}",
          "refreshToken": "${M365_REFRESH_TOKEN}"
        }
      }
    }
  }
}

clientSecret is optional. Public PKCE clients do not have one.

Direct mode is strictly a single-process fallback. It persists the authoritative refresh token at ~/.openclaw/state/m365-direct-token.json by default, using an atomic replacement and restrictive permissions where supported. Override the path with directTokenStatePath, M365_DIRECT_TOKEN_STATE_PATH, or Once present, the state token takes precedence over configuration and environment values. Multiple plugin processes must use broker mode so only one process owns refresh-token rotation.

Least-privilege permissions

Choose the narrowest delegated permission that supports the desired operation.

FeatureDesired capabilityMinimum Microsoft Graph delegated permission
mail-readList, search, read mail; download attachments; inbox webhookMail.Read
mail-writeMove or flag mail; also enables mail readsMail.ReadWrite
mail-sendSend, reply, or forward mailMail.Send
calendar-readRead calendars/eventsCalendars.Read
calendar-writeCreate, update, delete events or meetings; also enables readsCalendars.ReadWrite
tasks-readRead Microsoft To Do lists/tasksTasks.Read
tasks-writeCreate, update, complete, or delete tasks; also enables readsTasks.ReadWrite
onedrive-readList, search, inspect, read text, or download OneDrive contentFiles.Read
onedrive-writeUpload, create, move, rename, or delete OneDrive content; also enables readsFiles.ReadWrite
Login-onlyReceive a reusable refresh token during loginoffline_access

*.ReadWrite permissions include the corresponding reads, so selecting both read and write for the same feature is unnecessary.

Permissions are enforced in three independent layers:

  1. the plugin registers only tools enabled by its configured features;
  2. the broker rejects scopes outside its own M365_FEATURES allowlist before contacting Microsoft;
  3. Microsoft issues tokens only for delegated scopes actually consented by the signed-in account.

Configure the same feature list in the plugin and broker. The broker does not trust the plugin's list, and neither configuration can expand Microsoft consent. Unknown features and unrecognized broker scopes fail closed.

Azure permission configuration is not consent. Adding a delegated permission in Azure does not grant the account access by itself. Re-run npm run login with the new feature/scopes, complete the consent prompt, and replace the refresh token owned by the broker. Stop the service and update the refreshToken field in its state file while preserving subscription metadata, then restart it. Merely changing plugin configuration does not expand the scopes of an existing refresh token.

Personal Microsoft accounts normally consent during login. Work/school tenants can apply policies that require an administrator to approve some or all delegated permissions. If the consent screen says approval is required, a tenant administrator must grant consent before login can mint a usable refresh token.

For app-registration steps, account audiences, public PKCE clients, and confidential clients, see docs/custom-app-registration.md.

Configuration

Plugin fieldEnvironmentPurpose
clientIdM365_CLIENT_IDAzure application/client ID
clientSecretM365_CLIENT_SECRETOptional confidential-client secret
refreshTokenM365_REFRESH_TOKENDirect-mode refresh token
directTokenStatePathM365_DIRECT_TOKEN_STATE_PATH, then ~/.openclaw/state/m365-direct-token.jsonDirect-mode durable token state
tenantM365_TENANT, then consumersOAuth tenant such as consumers, common, or a tenant ID
tokenBrokerUrlM365_TOKEN_BROKER_URLBroker /token URL
tokenBrokerSecretM365_TOKEN_BROKER_SECRETBroker bearer secret
featuresM365_FEATURES, then calendar-write,mail-write,mail-send,tasks-writeEnabled tool capabilities; use the same list in the broker
personalCalendarNamesM365_PERSONAL_CALENDAR_NAMESExtra comma-separated personal calendar names
familyCalendarNamesM365_FAMILY_CALENDAR_NAMESExtra comma-separated family calendar names
accessβ€”Optional per-calendar read/write access control (see below)

Calendar deletion and attachment storage

OpenClaw requests capability consent at install. Microsoft Graph delegated permissions and the plugin's feature settings control which account operations are available.

  • Calendar event deletion and cancellation are off by default. Set allowCalendarDeletion: true for the assigned account only if it needs those operations. The tool requires one Graph event ID, the same ID as confirm_event_id to check the intended target, and calendar write access when an ACL is configured. Obtain explicit user confirmation before calling the tool. Deleting an organizer's event may notify attendees.
  • To let an account save Outlook attachments locally, set attachmentSaveDirectory to an existing private absolute directory controlled by the gateway operator, on a filesystem that supports hard links. Use a distinct directory for each account. On Unix, set mode 0700 to keep attachment names and contents private. The tool saves new files only and reports existing names it skipped. Omit output_dir or pass that same configured directory.

Set these options on the plugin config for the default account or in the corresponding accounts.<account-id> entry for a mapped account.

Calendar access control

Add an access block to restrict which agents and verified senders can read or write each calendar. The calendar ids are personal (the default calendar) and family. The rules come from carapace-plugin-sdk:

  • A grant is "*" or { "agent": ..., "sender": ... }. Every field in a grant must match, and any one matching grant allows the call.
  • agent is an OpenClaw agent id.
  • sender names an OpenClaw root-config accessGroups entry (type: "message.senders"), or the special name "owner".
  • Turns with no sender (cron, openclaw agent, heartbeat) match only grants with no sender field.
  • No access block allows everything, the same as before.
  • Default-deny applies once access.calendars exists. An unlisted calendar, or an op with no grant list, is denied.
json
{
  "accessGroups": {
    "jeff": { "type": "message.senders", "members": { "imessage": ["+14255550100", "jeff@example.com"], "discord": ["123456789012345678"] } }
  },
  "plugins": {
    "entries": {
      "m365": {
        "config": {
          "access": {
            "calendars": {
              "family":   { "read": ["*"], "write": ["*"] },
              "personal": { "read": [{ "agent": "main" }, { "sender": "jeff" }], "write": [{ "agent": "main" }] }
            }
          }
        }
      }
    }
  }
}

How each tool is checked:

ToolCheck
outlook_calendar_fetchread on calendar. With all (the default), only readable calendars are returned, and omitted_calendars lists the rest. It errors only when none are readable
outlook_query_eventsread on calendar (personal when omitted), in every mode: date range, text, uid. An explicit calendar now scopes uid and text queries to that calendar
outlook_create_eventwrite on calendar (default personal)
outlook_meetingwrite on personal
outlook_update_event, outlook_delete_eventDeletion and cancellation additionally require the safeguards above. The event's calendar is looked up first (GET /me/events/{id}/calendar), then write is required on it. Events on any other calendar are checked as other:<name> and are denied unless granted. The lookup only runs when access.calendars is set

A denial is returned as a tool error, for example Access denied: agent "family" / sender +14255550100 may not read calendar "personal". It carries no event data and is logged once through the plugin logger. The standalone CLI reads config from the environment, so it never has an access block and is not restricted.

Tools

Outlook mail, calendar, and task tools

All existing names remain unchanged:

  • Mail: outlook_inbox, outlook_search, outlook_read, outlook_save_attachments, outlook_send, outlook_reply, outlook_forward, outlook_move, outlook_flag
  • Calendar: outlook_calendar_fetch, outlook_create_event, outlook_update_event, outlook_delete_event, outlook_meeting, outlook_query_events
  • Tasks: outlook_task_lists, outlook_tasks, outlook_create_task, outlook_update_task, outlook_complete_task, outlook_delete_task

For personal or family conflict checks, call outlook_query_events with the calendar and inclusive after and before dates. The date range uses Pacific midnight boundaries and includes recurring occurrences. Calendar reads follow up to 50 Microsoft Graph calendar view pages and report an error if more pages are needed. Each Graph nextLink must use the original Graph origin and identify the same calendar view. The host and API version are case-insensitive. Other path segments, including the calendar ID, are compared case-sensitively after URL decoding. Graph's OData string-key form and the corresponding slash-separated path are equivalent. outlook_calendar_fetch reads a rolling window from today and accepts days_ahead as an alias for days.

OneDrive tools

These tools are hidden by default. Enable onedrive-read for the read tools or onedrive-write for both read and write tools, in both plugin and broker config.

OneDrive accepts item IDs or drive-root-relative paths. Parameters that offer both forms reject ambiguous requests containing both.

ToolMain parametersDescription
onedrive_listitem_id or path, limit, cursorList root or folder children
onedrive_searchquery, limit, cursorSearch files and folders
onedrive_metadataitem_id or pathGet item/root metadata
onedrive_readitem_id or path, offset, max_charsRead a bounded window of UTF-8 text (file limit 1 MiB)
onedrive_downloaditem_id or path, output_path, overwriteDownload locally; existing files are preserved by default
onedrive_uploadlocal_path, name, parent_id or parent_path, overwriteSimple upload up to 4 MiB
onedrive_create_foldername, parent_id or parent_pathCreate a folder with conflict behavior fail
onedrive_movesource item_id or path, new_name, destination parent_id or parent_pathMove and/or rename
onedrive_deleteitem_id or pathDelete an item

Remote paths reject empty, . and .. segments. Local downloads never overwrite unless overwrite=true. Uploads also refuse an existing remote name unless explicitly allowed.

Personal OneDrive configuration and exclusions

Use tenant: "consumers" (the default) for personal Microsoft accounts. For example, the plugin config portion of your OpenClaw configuration can be:

json
{
  "tenant": "consumers",
  "features": ["onedrive-read"],
  "oneDriveDeniedPaths": ["Private", "Documents/Financial", "Notes/passwords.txt"]
}

Paths are relative to your own drive root. Each exclusion blocks the exact file or directory and every descendant; it is not a glob or substring match. Matching is case-insensitive, NFC-normalized, treats backslashes as separators, and conservatively decodes percent escapes (including nested escapes). Unsafe or ambiguous paths fail closed. / or an empty exclusion blocks the whole drive. Omit the property or use [] for no exclusions; malformed configuration fails closed. Configure this in the plugin, not only in the token broker.

With exclusions active, all read entry points resolve fresh metadata and walk parent IDs to the authenticated user's root. Search and list omit denied or unverifiable entries, including remote/shared shortcuts; direct access reports an error. Missing ancestry, cycles, and ancestry deeper than 128 items are refused. Item IDs and misleading search parent paths do not bypass the checks. Reads/downloads use the verified item ID and recheck ancestry before releasing bytes. All OneDrive write handlers refuse operations while exclusions are configured, including when onedrive-write is enabled, to prevent move/rename routes around the policy. Use onedrive-read to keep write tools hidden.

These are application-level exclusions, not narrower Microsoft Graph OAuth permissions. The OAuth token still has the consented Files.Read or Files.ReadWrite scope; another client or direct Graph access is outside this safeguard. Exclusions do not remove previously downloaded files, cached output, or other copies. Graph has no atomic path-policy/content transaction: concurrent external moves/renames cannot be completely eliminated as a race. Changes to exclusions take effect on subsequent calls using the updated plugin config. No OAuth grants or deployed configuration are changed by configuring this option.

Reading and enumerating

onedrive_read accepts .txt, .md, .markdown, .csv, .tsv, .json, .jsonl, .xml, .yaml, .yml, .log, .html, .css, .js, .ts, .py, .sh, .sql, .ini, and .toml. It returns raw text, never renders HTML or executes code, and rejects invalid UTF-8 and binary control characters. Office, PDF, archives, images, UTF-16 files, and other binary formats are not extracted; use onedrive_download instead (100 MiB maximum). Size is checked before transfer and actual response bytes are bounded, even if metadata understates the size. No document-parser dependencies are added.

Text output defaults to 16,000 UTF-16 code units, with max_chars from 1 to 100,000. Pass the returned next_offset as offset to continue; null means finished. Each call fetches the whole file (up to 1 MiB), so changing files are not snapshot-consistent and a window may split a surrogate pair.

List/search return { count, items, next_cursor }. Repeat the same arguments (including query, folder and limit) with cursor: next_cursor until it is null. limit is a Graph page size from 1 to 200 (default 50 for list, 25 for search). Filtering can yield an empty page with a non-null cursor: continue that cursor. List enumerates immediate children; call it on returned folders to recurse. Search uses Graph's indexed name/content matching, not a complete filesystem scan.

Cursors are authenticated, bound to the request and configuration, expire after one hour, and stop working after a plugin process restart or config change. Restart enumeration in that case. A cursor is not a raw URL; arbitrary Graph routes and cross-host continuations are rejected. Policy checks are repeated on every page, at the cost of extra Graph requests and possible throttling for large trees. Graph JSON responses are bounded to 4 MiB.

Graph API references: children and paging, search, and file content.

Token and state behavior

  • Access tokens are cached by normalized delegated-scope set until shortly before expiration.
  • Token refresh is serialized, including across different scope sets, so rotating refresh tokens cannot be reused concurrently.
  • The webhook service atomically writes rotated refresh tokens and subscription metadata to one state file with restrictive permissions where supported.
  • Direct mode atomically writes its rotated refresh token to its own state file and is supported only when exactly one plugin process uses that state.
  • A normal shutdown preserves the Graph subscription. Restarted services reuse or renew it, avoiding notification gaps caused by delete-and-recreate.
  • Tokens and broker secrets are never written to logs.

Development

powershell
npm install
npm test
npm run build

npm test covers the plugin, shared token manager, OneDrive tools, and token broker. npm run build builds the shared auth package, plugin/CLI/adapter, and standalone webhook service.

Deploying a local build to OpenClaw

Install your local build as a packed, managed plugin instead of pointing plugins.load.paths at this checkout (which drags the dev node_modules into OpenClaw's update snapshots):

bash
npm run deploy              # build β†’ pack to out/m365.tgz β†’ print install command
npm run deploy -- --install # same, then run the install command

The install command is openclaw plugins install npm-pack:<repo>/out/m365.tgz --force. OpenClaw installs the pack into its managed plugin root along with the package's production dependencies. What goes in the pack is controlled by "files" in package.json; the deploy script lists the packed files and refuses to deploy if src/, tests/ or node_modules/ end up in it.

The pack contains only the plugin (dist/ with the shared auth package bundled in). The token broker/webhook service (services/m365-webhook) and npm run login are separate and keep running from this checkout; the plugin reaches the broker over HTTP via tokenBrokerUrl.

Multiple broker accounts

Set M365_ACCOUNTS_PATH for the webhook service to a JSON file with an accounts object keyed by account ID. Each account specifies statePath, rulesPath, pipelineWorkspace, logPath, features, brokerSecretEnv, clientStateEnv and notify: { channel, target }. An optional mailStorePath enables an account-specific SQLite store. Use distinct paths, secrets and client states. The file references credentials by environment variable name. Keep refresh tokens in the individual state files.

The broker serves POST /token/<account-id>. Set legacyTokenPath: true on one account during migration to preserve its previous endpoint, state and subscription. All accounts use the same webhook URL. The service routes notifications by subscription ID and validates the matched account's client state. An unknown subscription requests a retry only when its client state matches a configured account. Each account requires an allowedAgents array that limits its rule file's agent and decision routes.

In plugin config, use accounts.<account-id> with agents, tokenBrokerUrl, tokenBrokerSecret, features and optional calendar names and access rules. OpenClaw's agent context selects the account. Mapped agents use that broker exclusively. Use defaultAgents to explicitly assign agents to the default account. The plugin refuses unassigned agents when account assignments are configured. The local mail store and meeting invitation tools are unavailable to mapped agents.

For remote sign-in, use npm run login -- --device-code --token-file <new-private-path> with the account's scopes. Enable public client flows in the app registration first. The command shows the verification code and saves the refresh token to the new file with private permissions.

For example, include this mapping in plugins.entries.m365.config for an additional read-only mailbox called shared in the broker account file:

json
{
  "accounts": {
    "shared": {
      "agents": ["shared-assistant"],
      "tokenBrokerUrl": "http://127.0.0.1:18790/token/shared",
      "tokenBrokerSecret": "${M365_SHARED_BROKER_SECRET}",
      "features": ["mail-read"]
    }
  }
}

Use M365_SHARED_BROKER_SECRET as the service account's brokerSecretEnv and list shared-assistant in its allowedAgents if its rules route to that agent.