Connect Microsoft 365 to OpenClaw
Bring Outlook mail, calendar, contacts, OneDrive files, and Microsoft To Do into OpenClaw with per-agent access you control.
Connect Microsoft 365 to OpenClaw
Independent community plugin by Baumus
Your Outlook messages, calendar, personal contacts, OneDrive files, and Microsoft To Do tasks are part of your day. Bring the parts you choose into OpenClaw so your agents can help you find information and work with it—under access rules you control.
This plugin connects one signed-in Microsoft user to OpenClaw under administrator-controlled access rules. Grant named agents specific access to Outlook Mail, Outlook Calendar, personal Contacts, OneDrive, and Microsoft To Do. Access is denied by default. Changes require OpenClaw approval by default; sending, deleting, and responding always require call-bound approval. An administrator can turn off warning-level approval, so review that setting before granting write access.
For example, an authorized agent can find a file in an approved OneDrive folder, check an upcoming event, find an Outlook message or personal contact, or review permitted tasks. The plugin does not provide Teams, SharePoint, arbitrary Microsoft Graph access, or a service-principal connection.
Start here: Check requirements and install from ClawHub, then choose access, then verify a read-only request.
This is not an official Microsoft or OpenClaw product. It carries no enterprise, compliance, or security certification. Review supported behavior and limits before using it with important data.
Get started in three steps
1. Check requirements and install
You need a supported OpenClaw host (>=2026.10.5), Node.js (>=24.16.0 <25 or >=26.1.0), permission to edit its configuration, and an approved Microsoft Entra public-client app registration for the account you will connect. Check your local versions:
node --version
openclaw --version
Review the ClawHub listing, source, and declared capabilities. Then install the published package:
openclaw plugins install clawhub:@baumus/openclaw-microsoft-graph
Installation alone does not sign you in, grant an agent access, or make an incomplete configuration usable. Existing installations should review changes before updating; this guide does not silently upgrade them.
Earlier ClawHub validation notice: Older validation runs flagged contracts.tools as an unsupported manifest contract (manifest-unknown-contracts). OpenClaw requires this field to discover the plugin's agent tools. The upstream Inspector fix has merged, and the current local package validation reports no findings. Check the hosted result for each published version separately.
Automatic failure diagnostics (3.24)
Relevant Microsoft Graph failures automatically include serviceHealth evidence in the existing tool result; no extra agent call or tool is required. Local policy/approval denials and successful requests never trigger a privileged status probe. OAuth/token-endpoint failures are not evidence that mail, calendar, contacts, tasks or files are down.
The optional check uses Graph v1.0 service issues, requiring ServiceHealth.Read.All with administrator consent in an organizational tenant. This plugin currently uses delegated refresh-token credentials, not application credentials. Personal accounts and ambiguous common tenants are unsupported. Default Control UI sign-in does not add this permission. An operator must separately review/consent and provision an organizational vault credential explicitly containing the scope; this release never changes live consent, credentials or configuration. Data-operation tokens continue requesting only their existing service scope, including the read-only scope ceiling.
Without that existing grant the result reports not_authorized; credential/status failures report unavailable, unsupported account/service combinations report unsupported. These are not successful health checks and do not replace the original error. Checks add at most 1500 ms to the caller, use at most three bounded pages without retries, share concurrent checks, and cache sanitized results for 30 seconds using isolated vault-generation/service identities. Caller cancellation takes precedence without cancelling another caller's diagnostic. A rotating credential refresh is independent of diagnostic deadlines/cancellation: once started it may finish in the background under the normal 10-second token-request timeout, retaining its singleflight/capacity slot until settlement and durably saving any replacement refresh token. Expired diagnostics skip the status request after refresh. Genuine transport or publication uncertainty still follows the vault's existing fail-closed quarantine rules; a diagnostic timeout alone does not cancel the refresh.
Only fresh, unresolved Microsoft incidents with exact service/feature matches are returned as IDs, status and timestamps. Unknown feature names remain unmatched. An incomplete listing or no matching incident never means healthy; repeated 503s never imply a global outage. Provider titles, posts, impact descriptions, raw error bodies, URLs and account data are not agent-facing diagnostic content. Existing error/code, nextAction, retrySafety and mutationApplied remain authoritative. Uncertain writes must be read back before retrying and are never automatically replayed.
OpenClaw SDK migration: Version 3.16.0 uses the awaited getSessionEntryAsync reader for session-bound approval checks, eliminating the getSessionEntry deprecation warning. This API requires OpenClaw 2026.10.5 or newer. Earlier plugin releases remain available for older hosts; this change does not itself alter Microsoft permissions or stored credentials.
2. Choose access and connect Microsoft
Create the vault-key SecretRef and a default-deny policy for named agents. Begin with one read-only grant. OneDrive access requires immutable drive and item IDs, not just a folder name. Configure and enable the plugin, then follow the setup checklist in Plugins → Connect Microsoft 365 to OpenClaw. It shows the next actionable prerequisite before sign-in. Connect the approved Microsoft account only after the policy is saved and applied. Review the Microsoft permissions shown during sign-in.
The detailed configuration guide has the exact key command, policy example, host configuration, and sign-in steps. This plugin uses delegated access for one signed-in user; it does not support application permissions, client secrets, or unattended service-principal access.
3. Verify your first request
Wait until the Control UI confirms that the Gateway has applied your rules. Run the local checks, then ask an explicitly allowed agent for one read-only item within its grant. Confirm that an ungranted agent or resource is denied. A visible installed-plugin entry alone does not prove the running Gateway can serve the request.
OneDrive file downloads
An agent with read access to a OneDrive folder in the Control UI can use onedrive_download for any file type in that grant, including Word, PowerPoint, custom binary, and HTML files. Locate the file with list/search, then supply the exact rootLabel and relativePath. Downloads return an opaque media://inbound/... file reference, byte count, and SHA-256—not inline file bytes or a host path.
Downloading transfers untrusted bytes; it does not parse, render, execute, or grant trust to file content. Content inspection remains separately type-restricted. Subsequent uploads accept any syntactically valid MIME type but require their own write grant, native approval, protected source, and integrity checks. Missing MIME metadata falls back to application/octet-stream; malformed MIME metadata is rejected. Filename, folder, policy, size, timeout, cancellation, and integrity checks still apply.
Security model
- Every operation is checked against a credential-free, default-deny per-agent policy before plugin-side key selection, vault I/O, OAuth, or Graph access.
- Warning-level mutations require OpenClaw-native call approval by default. Operators may explicitly set
warningApprovalsRequired: false; critical delete, send, and respond operations always retain native call-bound approval. - One shared delegated OAuth credential serves every authorized read and write operation. The plugin requests only the operation-specific scope for each exchange.
- One AES-256-GCM encrypted vault record, one fail-closed lock, and one authenticated quarantine marker protect the rotating refresh-token lifecycle.
- Access-token caching is bounded and transactional: a token associated with a rotated refresh token is admitted only after durable vault replacement and verification.
- Every refresh durably publishes authenticated
in_flightstate before OAuth dispatch. New OAuth-only uncertainty may recover once on a later authorized operation after 60 seconds; its authenticated retry budget is consumed durably before dispatch. Crashes, legacy markers, exhausted recovery, uncertain local publication and changed vault bindings remain blocked for reviewed operator recovery. No data operation is replayed. - HTTP-200 OAuth responses require a 1–16 KiB RFC 6750
b64token/header-safe access token and a positive integerexpires_inno greater than 86,400 seconds. Cache residency is capped at one hour with a 60-second skew.
This simpler shared-credential model has an explicit tradeoff: compromise of the credential, vault key, or a plugin bypass can expose the union of Microsoft delegated scopes granted to that credential. The policy and write-approval gates constrain normal plugin behavior; they are not provider-side credential isolation.
Contacts tools include business/home/other postal addresses and Outlook-compatible business/home/primary fax numbers. Address writes require all five components (or null to clear); omit fields to preserve them. See contact address and fax semantics.
Contacts access is optional and denied for existing policies until an administrator grants it. Read requires delegated Contacts.Read; create, update, and delete require Contacts.ReadWrite. Existing vault credentials do not gain newly requested scopes automatically. After saving and applying a new grant, the Control UI shows missing scopes and guides the administrator through renewal on Microsoft’s device page without entering identifiers or CLI commands. Affected operations fail closed until reauthorization succeeds; the old vault remains in place until the new grant is verified and atomically published.
See architecture, OAuth access matrix, vault design, and support.
Configuration reference
Version 3.5.3 uses one Microsoft delegated OAuth credential and one encrypted local vault. The policy contains authorization rules only; it never contains credential locations or credential material.
Detailed prerequisites
You need:
- Node.js
>=24.16.0 <25or>=26.1.0. - OpenClaw
>=2026.10.5running as the OS account that will own the plugin state. - A Microsoft Entra app registration and one delegated user grant for the account the plugin will use. Application permissions, client secrets, certificates, and daemon/service-principal flows are not supported.
- GNU
passand GPG only if you choose the optional emergencyrestore-passbackup. Do not invoke that export when credentials must remain exclusively in the local encrypted vault. Normal setup and tool calls do not usepass. - Permission to edit the OpenClaw configuration and to review the third-party plugin's declared capabilities.
Check the local versions before continuing:
node --version
openclaw --version
Prepare the Microsoft delegated credential
- Register an application in Microsoft Entra and record its Application (client) ID. Select the tenant/account audience appropriate for your organization.
- In Authentication, enable Allow public client flows for your own app registration. This device-code flow needs no redirect URI, HTTPS callback, public endpoint, or client secret. An administrator may need to grant delegated consent first; tenant conditional-access and consent rules remain authoritative.
- Configure the policy and vault-key SecretRef below. Then open the Connect Microsoft 365 to OpenClaw plugin page in the OpenClaw Control UI and follow Connect to Microsoft below. The Gateway derives requested delegated scopes from the configured policy and stores the refresh token directly in the encrypted vault. No token is copied into a file or command argument.
Create the vault-key SecretRef
credentialVaultKey accepts a structured OpenClaw SecretRef only. A plaintext string in openclaw.json is rejected. The resolved value must be exactly 32 random bytes encoded as canonical, unpadded base64url (43 characters).
The built-in team secret store is the simplest supported provider. The following command generates the key without printing it and writes it as a secret-kind value:
node -e 'process.stdout.write(require("node:crypto").randomBytes(32).toString("base64url"))' \
| openclaw secrets store set MICROSOFT_GRAPH_CREDENTIAL_VAULT_KEY --kind secret --value-file -
Reference it with the complete object shape:
credentialVaultKey: {
source: "store",
provider: "default",
id: "MICROSOFT_GRAPH_CREDENTIAL_VAULT_KEY",
}
You may instead use an env, file, or exec SecretRef backed by a correctly configured OpenClaw secret provider. Do not replace the object with the resolved value. Back up the SecretRef provider independently from the encrypted vault; losing or changing this key makes the existing vault unreadable.
Create a version-2 default-deny policy
Use the shipped v2 example as a template, then replace every placeholder. Put the resulting policy object directly in plugins.json; do not add another $include inside that file.
A conservative OneDrive read-only policy looks like this:
{
version: 2,
rules: { default: "deny" },
services: {
onedrive: {
allowed_roots: [{
label: "documents",
path: "/Documents",
drive_id: "replace-with-immutable-drive-id",
item_id: "replace-with-immutable-root-item-id",
include_descendants: true,
permissions: { read: true, write: false, delete: false },
agents: {
"replace-with-openclaw-agent-id": {
permissions: { read: true, write: false, delete: false },
},
},
}],
},
calendar: {
agents: {
// "replace-with-openclaw-agent-id": { operations: ["read"], resources: ["me"] },
},
},
mail: { agents: {} },
todo: { agents: {} },
},
}
Use agent IDs from the OpenClaw host configuration; the plugin does not infer policy grants from local workspace content. For OneDrive, obtain the immutable drive and item IDs with Microsoft Graph Explorer or another tenant-approved administrative client; the display path alone is not an authorization boundary. Calendar grants may use me or exact calendar IDs. Mail, Contacts, and To Do use fixed signed-in-user /me routes. Contacts are limited to the default /me/contacts collection. Add only the operations and resources you intend to permit, and add the corresponding delegated scopes to the one credential.
Keep rules.default: "deny". include_descendants must be literal true; remove a root entirely if descendants must not be available. Leave agents_instructions absent unless trusted administrators control every writer to that root and you intentionally set agents_instructions: "trusted". This optional plugin feature applies OpenClaw's standard AGENTS.md instruction format to policy-pinned OneDrive content; it does not read, copy, or modify the host agent's local workspace AGENTS.md.
Configure and enable the plugin
Keep one include for the whole plugin section in openclaw.json. If you already use tools.allow, merge microsoft-graph into that existing allowlist instead of replacing unrelated entries.
{
plugins: { $include: "plugins.json" },
tools: { allow: ["microsoft-graph"] },
}
Create plugins.json beside openclaw.json. It contains all plugin settings, including other installed plugins and the complete Microsoft Graph policy:
{
// Preserve any existing plugins.allow, plugins.load, and other entries.
entries: {
"microsoft-graph": {
enabled: true,
config: {
enabled: true,
warningApprovalsRequired: true,
credentialVaultKey: {
source: "store",
provider: "default",
id: "MICROSOFT_GRAPH_CREDENTIAL_VAULT_KEY",
},
policy: {
version: 2,
rules: { default: "deny" },
services: {
onedrive: { allowed_roots: [] },
calendar: { agents: {} },
mail: { agents: {} },
todo: { agents: {} },
},
},
},
},
},
}
$include is OpenClaw host-config composition. The plugin receives the resolved policy object and does not read policy files itself. A single-file include at plugins lets OpenClaw's plugin installer and config writer update plugins.json. Nested includes inside plugins.json block those writes.
One-time migration before upgrading an existing installation
If your existing openclaw.json has plugins.entries["microsoft-graph"].config.policy: { $include: "./microsoft-graph-policy.json5" }, run the bundled migration helper before the first openclaw plugins update microsoft-graph. OpenClaw refuses the update's plugin-config write before new plugin code can run, and managed npm installs use --ignore-scripts; the plugin cannot silently migrate itself during installation.
From a checkout of this version of the plugin, run npm ci, then:
node scripts/migrate-plugins-include.mjs --config "$HOME/.openclaw/openclaw.json"
node scripts/migrate-plugins-include.mjs --config "$HOME/.openclaw/openclaw.json" --apply
openclaw config validate --json
openclaw plugins update microsoft-graph
The first invocation is read-only. The apply step creates plugins.json with all prior plugin settings and the resolved Graph policy, preserves the rest of openclaw.json including comments, and keeps a byte-exact, private backup of the old root config. Comments inside the old plugins section are preserved in the backup, not copied into the generated plugins.json. It does not delete the old policy file, update the plugin, restart the Gateway, change grants, or contact Microsoft. It refuses unexpected nested includes, an existing plugins.json, paths outside the config directory, and concurrent changes. Running it again after success reports already-migrated. Check that openclaw config validate --json returns valid: true before updating. If validation fails, restore the reported .bak file over openclaw.json; the original policy file remains available. Stop concurrent config edits during the migration and verify the plugin state after the update.
If your current layout differs from that exact legacy shape, do not force the helper; migrate manually after reviewing the actual include ownership.
If the plugin remains disabled after saving valid configuration, enable it explicitly and accept capabilities only after review:
warningApprovalsRequired defaults to true when omitted. Set it to false only when policy-authorized warning-level mutations should run without an approval prompt. This setting never affects critical approvals and never bypasses policy authorization, parameter validation, managed-root instruction checks, protected-media checks, or write preconditions.
openclaw plugins enable microsoft-graph
Sign in from the browser UI
Open Plugins → Connect Microsoft 365 to OpenClaw in an administrator Control UI session. Save the access rules and wait until the page confirms that the Gateway has applied them. Under Connect to Microsoft, enter the approved public application's client ID and tenant ID/domain, then select Start sign-in. Open the Microsoft link, enter the one-time code shown on this page, and approve the displayed delegated permissions. The page detects completion automatically; you can cancel before authorization finishes.
The Gateway, not the browser, polls Microsoft's token endpoint, verifies the granted scopes against the applied policy, and writes the refresh token directly to an empty encrypted local vault. The device-code flow makes outbound requests to Microsoft; it does not operate or require an inbound OAuth callback service. The UI only receives a one-time code, scoped status, and sanitized errors. It never receives OAuth tokens or the vault key. The code expires within 15 minutes. A CLI alternative remains available from an interactive host terminal:
openclaw microsoft-graph credentials status
openclaw microsoft-graph credentials sign-in --client-id <approved-app-id> --tenant <tenant-id>
Tenant consent and conditional-access rules remain authoritative. Initial sign-in will not overwrite an existing or quarantined vault. For an existing valid vault needing additional policy scopes, save and apply the policy, then choose Renew Microsoft permissions in the Control UI. The admin-scoped renewal action reuses the app and tenant from the encrypted vault, not browser storage; no identifiers or commands need to be entered. Open the Microsoft link, enter the displayed code there, review the permissions, and return to the UI for the verified result. Cancellation, expiry, and sanitized failures are shown in that same flow.
Use the same Microsoft account on Microsoft's device page. The Gateway requests all scopes required by the active policy, checks Microsoft's returned scopes, and replaces the existing credential only after successful consent. It refuses a different app/tenant, quarantined vault, stale vault binding, or changed policy; an unsuccessful sign-in leaves the original credential in place. The existing vault does not record an independently verified account identity, so the operator must confirm the account shown by Microsoft. Codes stay on the local authenticated UI and Microsoft's page, not chat. status requires operator.read; sign-in, reauthorization, cancellation, recovery, and optional restore-pass require operator.admin. Gateway RPC parameters and responses have closed validated shapes and do not include OAuth tokens, the vault key, pass contents, or raw errors. Existing explicit-ID CLI callers remain supported for compatibility; the UI does not require that fallback.
missingScopes compares the active policy with scopes stored when Microsoft issued the credential; it does not call Microsoft to detect a later consent revocation. If Microsoft subsequently denies an operation despite missingScopes: [], check the policy, account, and tenant first. The Control UI also keeps a collapsible renewal action available for that case.
Agent-facing tool errors distinguish missing stored consent, blocked credential refresh, and Microsoft HTTP 401/403. They point to credential status and the guided operator flow; a provider denial alone is not treated as proof that reauthorization is required.
Validate the setup
Run the local checks in this order:
openclaw config validate
openclaw plugins doctor --json
openclaw plugins inspect microsoft-graph --runtime --json
openclaw secrets audit --check
openclaw microsoft-graph credentials status
Expected credential status is result: "valid" with missingScopes: [] and secret-free metadata. Then, from an agent explicitly granted in policy, make one read-only request against an allowlisted resource and confirm that an ungranted agent or resource is denied. Do not start validation with a write or destructive action. plugins list or a cold manifest inspection alone does not prove that the running Gateway registered the plugin.
Understand approvals
Agents must start with microsoft_graph_capabilities({}) to discover their own effective root labels, configured rootPath, service actions/resources, and prerequisites. Use rootPath to identify the requested folder and pass the exact returned rootLabel; agent IDs, folder titles, and paths are not labels. For example, /Synthetic/Studio may be exposed as folder_42 to agent studio. Ask if discovery is unavailable, the requested root/action is absent, or the folder match is ambiguous; never guess or broaden access. A local access_denied calls for rediscovery and policy review, not an unchanged retry, automatic reauthorization, or a claim that the UI contradicts enforcement. It never checks sign-in, accesses credentials, or calls Graph; connection and sign-in remain operator-owned. Saved grants opt in this discovery helper alongside operation-specific tools; trusted roots also opt in onedrive_agents_instructions only for callers with read permission. Existing explicit denies still win. Trusted instructions require read authorization even for write/delete operations; write-only callers receive that prerequisite, not implicit read access. Existing installations are reconciled when an administrator opens the Control UI or checks status after the saved policy is confirmed active. All concrete tools include action, exact-ID discovery, approval, result, and next-step guidance, so no bundled skill is required.
Mutation schemas accept optional timeoutMs as OpenClaw outer transport metadata, not a Graph parameter or approval. Set at least 180000 for calls that may wait through the native 120-second approval prompt, and include expected execution time up to the host's ordinary 600-second cap. The host default is 90 seconds; timeoutSeconds adds 30 seconds but is not part of this plugin's schema. The plugin strips timeoutMs before semantic validation, approval snapshot binding, and provider payload construction. Long OneDrive transfers configured for up to 24 hours cannot fit a single ordinary dynamic tool call; if the outer call ends, read back the exact target before retrying. A larger timeout never grants permission or extends an expired approval.
Results retain their previous fields and add phase, code, nextAction, retrySafety, and mutationApplied (true, false, or "unknown"). A send receipt means Graph accepted the request, not recipient delivery; inspect Sent Items before any uncertain retry. Paginated reads set noResults only when an empty page is complete; follow continuation or narrow a capped query when completeness is partial or unknown. Calendar multiwrite remains non-atomic: inspect each operation and retry only after readback.
| Class | Examples | Required user action |
|---|---|---|
| none | Explicitly recognized read actions | No mutation approval; policy authorization still applies. |
| warning | Create/update/draft/move/mark operations | By default, use OpenClaw's native approval and choose allow-once, allow-always, or deny. With warningApprovalsRequired: false, no approval is requested. |
| critical | Delete, send, and calendar respond operations | Use OpenClaw's native call-bound approval and choose allow-once or deny. Warning configuration and legacy chat fields cannot downgrade or replace this approval. |
For warning requests, allow-always trusts only the authenticated agent ID, exact tool name, and normalized action (for example, outlook_mail_write + mark_read). It does not trust a resource, arbitrary future action, or another agent/tool/action. Trust is held only in plugin process memory and is revoked by plugin reload or process restart; it is not written to OpenClaw config or disk. Every trusted future call still runs authorization, validation, managed-root instruction discovery, protected-media validation, and execution preconditions. Approval-free trusted/configured warning calls also require the host's call identity so the plugin can bind and reverify their exact execution parameters. Critical calls never offer allow-always.
The deprecated chatConfirmed and chatConfirmationToken tool fields remain accepted for compatibility but are ignored and can never authorize execution. The plugin returns the exact parameters it inspected with each native approval so OpenClaw freezes that snapshot while approval is pending. It also binds the host tool-call identity to that snapshot and consumes it at execution; any later composed rewrite fails closed before plugin execution. If no approval route is available, or approval is denied, cancelled, malformed, or times out, the host blocks the call. For critical deletion, the host approval client must carry operator.approvals; a missing scope is an authorization failure, not Gateway unavailability. The plugin cannot grant this host scope or bypass a failed approval. After repairing the host approval route, request a fresh allow-once approval for the exact deletion.
Native approval text identifies the mutation action, a minimized target, and the relevant risk without including message bodies, event bodies, subjects, recipient addresses, or To Do titles. OneDrive upload/update approvals include the allowlisted root, relative path, plugin-computed SHA-256, and byte size. For an agent-created workspace file, agents make one onedrive_upload (or onedrive_update) call with rootLabel, destination relativePath, and sourceWorkspacePath relative to their own workspace, for example reports/onepager.pdf. The plugin securely stages, hashes, requests native approval, and transfers the file without a separate staging call. Workspace staging is limited to 64 MiB per file and 128 MiB and 64 files in aggregate across gateway processes sharing the same state directory (including concurrent reservations, pending approvals, and orphaned copies); larger files must already exist as private media. Plugin-created copies are removed after denial, cancellation, timeout, failed preflight, or execution. Files already returned as media://inbound/... use sourceMediaUri instead and are never deleted by this cleanup. Supply exactly one source; sourceSha256 and sourceByteSize are optional paired assertions. Do not construct a media:// URI from a workspace filename. Preflight and execution each securely open the protected artifact and fail before their downstream credential or Graph boundary if that exact content identity does not match. A failed preflight does not request approval. Calendar approvals include calendar/event identity, and multiwrite approvals include the operation count. Mail send approval identifies that recipients come from the stored draft and explicitly notes that the recipient count is unavailable from the send call itself.
Staged workspace copies live in a plugin-owned inbound subdirectory. On startup and hourly, the plugin reconciles marked runs from stopped processes, including interrupted uploads. Live processes retain their copies; when process identity cannot be checked (for example across hosts), only runs inactive for eight days are eligible. Shared staging-quota locks carry a process identity and are reclaimed when that owner is provably gone; an empty lock left before its owner marker was written is eligible only after eight days. Locks with unverifiable owners or foreign contents are left alone rather than stolen. Unmarked directories, foreign files, and caller-supplied inbound media are left alone. Cleanup failures are retried on later scans.
OneDrive mutation authorization occurs before a warning approval request or approval-free warning continuation. For upload/update, the protected artifact's opened-file identity, exact lowercase SHA-256, and byte size are verified before any applicable managed-root instruction discovery. Discovery requires its own read authority before credential or Graph access. Execution independently reopens and revalidates the artifact plus policy authorization and all media/write preconditions before selecting the key, reading the vault, exchanging OAuth, or calling Graph.
10. Status, recovery, and rollback
openclaw microsoft-graph credentials status returns one of:
missing: no vault exists; use the browser sign-in above.validwith nonemptymissingScopes: the saved policy requires consent absent from the stored credential; use Renew Microsoft permissions in the Control UI. Do not delete the vault.valid: the vault decrypts and has no authenticated refresh marker.quarantined: an authenticated refresh marker exists. A new explicitly OAuth-uncertain marker permits one bounded recovery on a later authorized operation after a 60-second cooldown; other markers remain blocked. Status itself does not attempt OAuth or clear state.unavailable: the key, record, permissions, ownership, filesystem, or authenticated envelope could not be validated. Stop and investigate; do not overwrite the vault.
For quarantined, the ordinary reauthorize command refuses to replace the vault. Automatic recovery is only for authenticated v3 OAuth-only uncertainty matching the exact current vault generation, key and digest. It never runs in the background or retries a Graph data request; failure exhausts its one durable attempt even across process restart. Microsoft documents that issuing a new token pair does not automatically revoke the previous refresh token (refresh-token lifecycle); the recovery may still receive a real reauthorization error. Definitive invalid_grant / interaction_required responses on an ordinary fresh refresh require guided sign-in instead, and do not leave an OAuth marker blocking that flow. A failed claimed recovery never clears its consumed retry budget, even for a definitive authentication/reauthorization error; exhausted state requires reviewed operator recovery before guided sign-in. Legacy v1/v2 markers cannot distinguish an uncertain OAuth response from an uncertain local credential publication, so they are never cleared automatically. Arrange separately reviewed recovery or replacement for all remaining blocked states. Only if an operator has independently established that the current vault credential remains usable should they copy the current sanitized binding from status and run:
openclaw microsoft-graph credentials recover-refresh --expected-binding <binding> --dry-run
openclaw microsoft-graph credentials recover-refresh --expected-binding <binding> --apply
Apply requires the exact typed confirmation RECOVER MICROSOFT GRAPH REFRESH. The binding prevents recovery against a changed record. Do not blindly repeat a refresh or recovery after an uncertain result. A package downgrade to 3.20.1 or earlier rejects v3 markers and fails closed: finish verified recovery first, or use separately reviewed operator recovery with the current package. Never delete or downgrade a marker to reset its retry budget.
To create a verified emergency copy in a separate pass destination without changing vault operation:
openclaw microsoft-graph credentials restore-pass --destination <pass-ref> --dry-run
openclaw microsoft-graph credentials restore-pass --destination <pass-ref> --apply
Apply requires RESTORE MICROSOFT GRAPH CREDENTIAL. A complete receipt means the destination was written and read back; unknown means the local result could not be verified and must be inspected before retrying. The plugin never deletes a pass entry automatically.
Safety notes
- Keep the SecretRef provider, vault files, and any
passbackup private and backed up separately. Never store the key beside an exported vault backup. - Vault generations have no external monotonic anchor. Replaying an older valid encrypted record with its matching key cannot be detected cryptographically; compare sanitized bindings and prefer reauthorization after uncertainty.
- One shared credential has the union of its consented Microsoft scopes. Policy and approval gates constrain normal plugin use but do not provide provider-side read/write isolation after credential, key, host-account, or plugin compromise.
- OpenClaw may resolve declared SecretInputs while loading configuration. The plugin guarantees authorization before plugin-side key selection and vault/provider access, not suppression of host-level SecretRef materialization.
- Unknown actions, malformed resources, missing grants, missing credentials, unsafe files, and unsupported filesystem conditions fail closed.
- Process-local access-token, continuation, instruction, and warning allow-always trust is lost on restart. Retry from a fresh read/status check rather than assuming an interrupted mutation failed.
Attach original Outlook emails to an existing draft
Use outlook_mail_write with add_message_attachment. Resolve the original IDs using outlook_mail_read, and use an existing draft ID (including the ID returned by reply_all_draft):
{ "action": "add_message_attachment", "messageId": "<existing-draft-id>", "sourceMessageId": "<original-message-id>", "attachmentName": "original-message.eml" }
The plugin reads the original message's complete Microsoft Graph MIME (/$value) and attaches those unchanged bytes as a message/rfc822 .eml file. Headers, body and embedded attachments are retained as supplied by Graph; the message is not reconstructed from selected fields. attachmentName is optional (default original-message.eml) and must be a leaf .eml name. This action requires both Mail read and update policy access, delegated Mail.ReadWrite, and the normal native warning approval. Both IDs and the optional filename are bound to the approved call. It validates that the target is still a draft before reading and again before attaching; it never sends mail or edits recipients/body.
One original is attached per call. MIME can be up to Microsoft Graph’s 150 MB attachment maximum (157,286,400 bytes). The plugin automatically uses a direct attachment below 3 MiB and a chunked upload session at or above 3 MiB; larger originals are rejected before any upload. Microsoft mailbox/message-size policies can impose a lower limit (the typical default message limit is 35 MB), which the plugin cannot override. attachmentDownloadTimeoutMs bounds the complete read-and-upload operation (default 10 minutes); each MIME read/upload request remains separately bounded (default 30 seconds, configurable through requestTimeoutMs). Include a sufficient outer tool timeoutMs for a large original. Call separately with distinct names for multiple originals. A failure after an attachment POST can have an unknown outcome: inspect list_attachments on the draft before retrying to avoid duplicates. Concurrent edits/sends by another client cannot be locked atomically; review the completed draft before sending. MIME bytes are never returned in model-facing results or logged.
Attach a file from the calling agent workspace
Call outlook_mail_write with a finished workspace-relative file:
{ "action": "add_attachment", "messageId": "<returned-draft-id>", "attachmentName": "report.pdf", "sourceWorkspacePath": "reports/report.pdf" }
Supply exactly one of sourceWorkspacePath or an existing attachmentMediaUri. Workspace sources use the existing private automatic staging mechanism (64 MiB per file and shared staging quotas); existing media sources retain the 150 MB Outlook limit. Absolute host paths, traversal, symlinks and hardlinks are rejected. The trusted calling agent/session selects the workspace, not tool arguments. Common extensions infer MIME; supply attachmentContentType to override it.
The plugin computes SHA-256 and size before native approval, binds the exact call including its original relative path and private artifact, and rechecks bytes before credentials or provider access. Optional sourceSha256 and sourceByteSize are paired assertions, not prerequisites. Native approval remains authoritative; no chat tokens, Base64 arguments, extra Microsoft scopes or manual staging are needed. Approved content is the private snapshot: later edits to the original workspace file do not change it. A changed staged artifact requires a fresh call. Plugin-owned copies are cleaned on settlement or bounded expiry. This action adds an attachment to the draft and never sends it.
Place images within an Outlook mail body
Use an HTML draft and a matching CID attachment. Put <img src="cid:chart-1" alt="Chart"> at the precise position in bodyHtml where the image should appear, then add the private image to that draft with inlineContentId: "chart-1":
{ "action": "create_draft", "subject": "Results", "bodyHtml": "<p>Here are the results:</p><img src=\"cid:chart-1\" alt=\"Chart\"><p>What do you think?</p>" }
Use the returned draft messageId in a second outlook_mail_write call:
{ "action": "add_attachment", "messageId": "<returned-draft-id>", "attachmentName": "chart.png", "attachmentContentType": "image/png", "attachmentMediaUri": "media://inbound/<actual-private-media-id>", "inlineContentId": "chart-1" }
The media URI must be a real OpenClaw private-media artifact, not a path or invented URI. PNG, JPEG, and GIF are supported for inline placement; the plugin checks their file signatures. Each image needs a distinct CID, and the same CID must appear in its HTML <img src> reference. For an existing draft, use update_draft to position or reposition the reference, then add_attachment for a new image. Ordinary attachments omit inlineContentId and retain their previous behavior. Review the completed draft before send_draft; draft changes and attachment upload are separate writes, so either can succeed if the other fails. Rendering details can differ between email clients.
Creating a task in the default To Do list
Use the existing microsoft_todo_write tool with action: "create_task", title, and exactly one of listId or listSelector: "default":
{ "action": "create_task", "listSelector": "default", "title": "Prepare meeting notes" }
The default selector requires independently allowed To Do read and create operations. Before native approval, the plugin validates the task payload and follows at most 20 safe list pages / 500 lists to identify the unique owned, non-shared list whose Microsoft wellknownListName is defaultList. Missing, ambiguous, unsafe, or incomplete discovery fails closed; list names and arbitrary sole lists are never used as fallback. Approval identifies and binds the concrete list ID, and execution uses that same target even if the account's default changes. The existing owner check remains; no post-write GET is added. Known listId calls do not discover lists or require separate discovery read access. The selector is not accepted for other actions. Warning approval and per-service overrides continue to apply.
Configuration UI (OpenClaw 2026.10.5+)
Administrators can enable Settings → Labs → Custom plugin UI, then open Connect Microsoft 365 to OpenClaw in the Control UI. The page offers English, German, Spanish, and Arabic; other host locales fall back to English. When a newer security-clean stable release is published on ClawHub, an administrator-only, read-only Gateway check shows an update badge beside the established-connection status. It contacts ClawHub with no Microsoft credentials or policy data, and the badge never installs or activates an update. The page edits OneDrive folder/agent rights, per-agent Calendar/Mail/Contacts/To Do access, and warning-level approval choices for each service. On Services, Calendar shows the effective scope for the selected agent: a grant without resources means default calendar only. An admin-only Gateway lookup retrieves calendar IDs and names (never events); selecting a calendar changes only that agent's resource list, not its operation rights. Unavailable lists do not imply full access, and configured IDs absent from the list remain visible and retained unless explicitly unchecked. The Review step names added and removed calendar grants before save. New OneDrive paths are resolved to immutable drive/item IDs by an admin-only Gateway method. Critical delete, send, and respond actions always retain call-bound approval.
The page validates the policy and submits one revision-checked config.patch for the policy and any missing, operation-matched OneDrive tool opt-ins for granted agents. A supported single-file object-key $include is written through by OpenClaw; an unsupported include layout or concurrent change fails closed. The page immediately locks duplicate writes and re-reads the effective policy independently of the save response. A timeout or disconnect does not imply that saving failed: unknown outcomes are reconciled without resaving. Drafts and operation state remain only in authenticated host memory across page remounts (not browser storage). An administrator-only read-only status method compares the running Microsoft Graph generation’s canonical policy hash with the saved target; unrelated Gateway changes do not make Graph rules appear inactive. Pending application is checked automatically for up to 12 checks, with bounded read timeouts and a manual recheck available. After a persisted save, the page can request a targeted, drain-aware plugin reload; Apply saved rules retries application without rewriting policy or interrupting admitted work. A disconnect during application may require another application attempt. Concurrent policy changes fail closed and require loading the current state. Confirmed Microsoft account connection remains visible during pending activation. Do not treat “saved” as proof that the Gateway is using the new rules.
When new delegated scopes are required, the page warns before saving. After the policy is applied, it displays the missing scopes and a guided renewal action; affected tools remain denied until the new grant is verified. Initial sign-in remains create-only; renewal reuses the existing app/tenant and requires administrator authority. Tokens and the vault key stay on the Gateway. Generic plugin settings and CLI paths remain available when Custom plugin UI is disabled.
Development
npm ci
npm test
npm run typecheck
npm run build
npm run plugin:build:check
npm run plugin:validate
npm run package:check
npx --no-install clawhub package validate .
Tests use synthetic fixtures and mocked provider boundaries. They must not use real credentials or call Microsoft Graph.
License
Apache-2.0. See LICENSE.
Automatic tool-access reconciliation
The saved Microsoft access policy is the source of truth for this plugin's exact tool opt-ins. When an authenticated administrator opens the native Control UI, checks status, or completes a save, the UI first verifies the active policy fingerprint and then repairs missing or obsolete exact Microsoft Graph tool entries across the configured agents. This is an administrator-UI lifecycle mechanism, not a continuous background daemon. It does not contact Microsoft or change access resources, Microsoft consent, approvals, global policies or explicit denies.
Only exact Graph tool names are synchronized, using the union of all saved grants for each agent. Unrelated names, wildcard/group grants and non-Graph settings stay untouched. Denied tools remain denied and appear by agent/tool in the warning; valid peers can still heal. Missing or conflicting agent configurations require administrator review rather than invented entries. Removing the final restrictive tools.allow entry is also blocked: Core treats an empty allowlist as unrestricted, so the UI asks the administrator to choose the intended tool policy first instead of widening access. Other host policy layers can still restrict effective execution; a repaired opt-in is not a provider-access test.
Each repair uses the existing authenticated, private activation journal and one native config CAS. Root agent tools and included plugin policy are never combined in a repair write. Uncertain writes are observed without automatic replay; a changed revision, revoked administrator session or pending save stops dispatch. The UI confirms persistence separately from application and never forces a restart, interrupts retained work or schedules an extra plugin reload. If a repair remains ambiguous, use the current-state review action; do not repeatedly save the rules.
Complete contact fields
The contact tools expose every scalar/structured property of the Microsoft Graph v1.0 contact resource. See contact field coverage for writable fields, clearing semantics, metadata, and relationship boundaries.
Native reply history (3.25.0)
reply_draft and reply_all_draft now create a native Microsoft reply with no replacement body. Supply only the new answer in bodyHtml (an HTML fragment) or bodyText; never reconstruct or include the quote. The plugin reads the created draft and inserts the new answer immediately inside its existing <body> without sanitizing, reformatting or fetching the provider history. Omit both body fields to create the native draft unchanged.
{"action":"reply_draft","messageId":"resolved-original-id","bodyHtml":"<p>Thank you for the update.</p>"}
To insert new content above an existing draft, use prepend_reply_draft with that draft's messageId and only the new fragment. This action prepends; it does not replace previous answers and is not idempotent. update_draft still replaces supplied fields and retains its original authored-HTML validation; do not pass copied history to it.
Remote signature images, Outlook CSS/conditional comments and CID references in existing history pass through unchanged. Existing inline attachments are left on the same native draft, not downloaded or recreated. Attachment listings expose contentId when Microsoft provides it. New authored remote images remain blocked. New reply fragments cannot contain document wrappers, style blocks or event handlers. No new Graph scopes or agent grants are required.
New content remains bounded to 65,536 characters; the internally retained history plus answer has a separate 4 MiB UTF-8 limit and is never truncated to fit. This is an insertion operation, not an after-write history comparison or concurrent-edit locking feature. No Outlook UI certification is claimed, and client-managed signatures are not generated by the plugin.
If native creation succeeds but content insertion fails, draftCreated: true and item.id identify the retained draft. Inspect that exact draft before any retry; do not create another reply or blindly prepend again. The operation never sends or deletes a message. Update existing callers that previously supplied a full composed body: supply only the new answer instead. Rollback is the prior plugin release, with callers restored to its previous composition contract.
