Skip to main content

MCP server for SharePoint document libraries with audit-preserving checkout/checkin.

Project description

mcp-server-sharepoint

PyPI version Python versions Downloads Licence CI Coverage Contributions welcome

In one sentence: an MCP server that lets AI coding agents like Claude Code edit files in your SharePoint document libraries the same way a careful human would — with proper checkout, comments, version history, and lock conflicts — instead of overwriting things and breaking your audit trail.

What is this for?

You have important documents in SharePoint — ISO 27001 controls, contract templates, ISMS records, runbooks, a quality manual. They have version history, audit trails, retention policies, and someone above you cares that they stay compliant.

You'd love to let AI agents help you draft and update these documents — they're great at it. But every other "AI + SharePoint" tool you've tried makes the audit log say "a robot named rclone updated this file at 03:42 with no comment" — which means your auditor has questions.

mcp-server-sharepoint makes the audit log say what actually happened: "David Koller updated this file at 14:32. Comment: ‘Tightened control wording for A.5.1 per CISO review.’ Version: 3.5 → 3.6 (minor)." Because the AI agent uses the same Microsoft-blessed checkout/checkin model a human Office user would.

Concretely, the agent gets these tools:

Tool What the agent does What ends up in SharePoint
sp_search, sp_list, sp_read finds and reads files nothing changes
sp_open acquires a checkout lock + downloads "checked out by you" appears for everyone else
sp_save uploads + checks in with a comment a real new version with a real comment in the audit log
sp_release discards a checkout lock released, no version created
sp_status shows what's currently checked out by this agent nothing changes

Every action is attributed to the human who signed in once via Microsoft's standard Device Code login. No service-account "robot" identity. No silent overwrites. No broken locks. Lock conflicts are reported as conflicts. ETag checks catch concurrent edits before they clobber.

Installation

pip install mcp-server-sharepoint
# or, with uv (recommended):
uv tool install mcp-server-sharepoint
# or, on the fly without installing globally:
uvx mcp-server-sharepoint --help

Requires Python 3.11+. Works on Linux, macOS, Windows.

Quickstart

1. Sign in once (out of band)

uvx mcp-server-sharepoint login

Output looks like:

Sign in to mcp-server-sharepoint via the Device Code flow:
Open the URL in a browser and type the code.

     URL:   https://login.microsoft.com/device
     Code:  D2LKUY4AV

Waiting for sign-in...

Open the URL in any browser, type the code, sign in with your M365 account. Your refresh token is cached locally — see Token storage. The MCP server itself never blocks for human interaction afterwards.

2. Wire it into Claude Code

In your project's .mcp.json:

{
  "mcpServers": {
    "sharepoint": {
      "command": "uvx",
      "args": ["mcp-server-sharepoint"]
    }
  }
}

Restart Claude Code. The agent now has sp_search, sp_list, sp_read, sp_status available — read-only by default.

3. Enable writes (when you're ready)

{
  "mcpServers": {
    "sharepoint": {
      "command": "uvx",
      "args": ["mcp-server-sharepoint"],
      "env": { "SP_ALLOW_WRITES": "true" }
    }
  }
}

Now sp_open, sp_save, sp_release are also available.

4. Try it

You:    Find our latest ISO 27001 control A.5.1 policy in SharePoint.
Agent:  [calls sp_search → finds it]
        Found "iso27001-A.5.1.md" at https://contoso.sharepoint.com/...

You:    Read it, suggest two improvements based on the new revision of the standard.
Agent:  [calls sp_read → reads file → suggests in chat]

You:    Apply them and save with a comment summarising the changes.
Agent:  [calls sp_open → modifies → sp_save with comment]
        Saved version 1.4. Comment recorded: "Tightened wording per ISO 27001:2022 to match new control objective; added cross-reference to A.5.2."

Each tool call gets a permission prompt in Claude Code (you can mark trusted ones as "always allow" per session). Read tools are flagged read-only; write tools are flagged destructive — you see the difference.

What it can do, in detail

Read tools (always available)

Tool Purpose
sp_search(query, site?, folder?, file_type?, modified_after?) KQL-style search across SharePoint sites the user has access to. Returns hits with name, path, web URL, last-modified date, author.
sp_list(url) List a SharePoint folder's children (files + sub-folders) with size, type, last-modified. URL is the human-readable web URL.
sp_read(url) Download a file's content to a local temp file with the original extension preserved. Read-only — does NOT acquire a checkout.
sp_status(verify=False) Show what files this agent currently has checked out, when, and where the local working copies are. With verify=True, additionally queries SharePoint to confirm the server-side lock state — adds server_locked (true/false/null) and lock_holder (display name) to each entry. Costs one Graph call per registry entry.
sp_sites(query?) Discover SharePoint sites the user can see. query is a free-text site-name search; omit to list all. Useful as the agent's starting point when no site URL is known yet.
sp_subsites(parent_site_url) List immediate sub-sites under a parent site URL. Recurse on each result's web_url to walk deeper.
sp_followed_sites() List sites the user has Followed in SharePoint — a curated "my SharePoint" entry point. Not available in service-principal mode (no signed-in user).
sp_drives(site_url) List the document libraries (drives) on a site — default Shared Documents plus Site Assets, Style Library, and any custom libraries. Most read/write tools accept URLs into any library transparently; sp_drives is the discovery step when the agent doesn't yet know which libraries exist.
sp_trash_list(site_url) List items in the SharePoint site's recycle bin (id, name, size, deleted_date_time, deleted_from_location, deleted_by). Read-only. Uses Graph beta endpoint — see note below.
sp_lists(site_url) List all SharePoint Lists on a site (id, name, display_name, web_url, description, template).
sp_list_columns(list_url) Schema of a SharePoint List — column definitions (name, type, required, hidden, etc.). list_url shape: https://<host>/sites/<name>/Lists/<list-name>.
sp_list_items(list_url, filter?, top?) List items in a SharePoint List with full fields expansion. filter is an optional OData expression like "fields/Status eq 'Open'".
sp_get_item(list_url, item_id) Fetch a single SharePoint List item with all expanded fields.
sp_permissions(url) List who has access to a SharePoint file, folder, or site. Pass a site URL for site-level permissions or any item URL for that item's permissions. Returns each permission with id, roles (read/write/owner), grantee ({type, display_name, email, link_type, link_scope, link_web_url}), and inherited flag. Read-only.
sp_share_list(url) List existing sharing links on a SharePoint file or folder — id, web_url (the share URL), type, scope, roles. Read-only. Use sp_share_create / sp_share_revoke for the write side.
sp_pages_list(site_url) List all modern SharePoint Pages (Site Pages) on a site — id, name, title, web_url, description, page_layout, last_modified.
sp_page_read(page_url) Fetch a single SharePoint Page including its canvasLayout (sections, columns, web parts) as raw JSON. page_url shape: https://<host>/sites/<name>/SitePages/<page>.aspx.
sp_changes(scope_url, since?) Microsoft Graph delta query — returns items in the site's default drive that changed since the optional cursor. First call (no cursor) returns the full item set + an initial cursor. Subsequent calls with the cursor return only created/modified/deleted items since. Cursor is opaque — store it (typically in the agent's conversation memory) and pass it back. Stale cursor surfaces as 410 Gone; drop it and re-sync from scratch.

Non-default libraries

URLs into non-default document libraries (Site Assets, Style Library, custom libraries) work transparently across sp_list, sp_read, sp_open, sp_save, sp_publish, etc. The resolver tries the default Shared Documents drive first; on a 404, it lists the site's drives, matches the URL's first path segment to a library name, and retries against that library. One extra Graph round-trip per first-look-up at a non-default library — acceptable cost for the convenience.

Write tools (opt-in via SP_ALLOW_WRITES=true)

Tool Purpose
sp_open(url) Acquire a server-side checkout lock + download the current content to a working-directory path. Other users see "checked out by you" until you save or release. Fails with a clear error if someone else already holds the lock.
sp_save(url, comment, version="minor"|"major") Upload your changes + check the file back in with an audit comment + new version. comment is required and must be non-empty — describes what changed for the audit log. ETag round-trip catches "someone else changed the file underneath us" and refuses to clobber.
sp_release(url) Discard a pending checkout: drop the lock server-side and delete the local working copy. Use when you decide not to keep your edits.
sp_open_many(urls) Bulk variant of sp_open — acquires checkouts on multiple files in parallel (up to 4 concurrent Graph calls per Microsoft throttling guidance). Returns one result per URL: {path, status: "ok"|"error", local_path?, error?}. Per-file failures don't abort the batch. Honors Retry-After on 429/503.
sp_save_many(operations) Bulk variant of sp_save — each op {url, comment, version?}. Same parallel/error-isolation semantics as sp_open_many. ETag round-trip applies per file.
sp_create_item(list_url, fields) Create a new item in a SharePoint List. fields is a dict of column-name -> value pairs (use sp_list_columns to inspect schema).
sp_update_item(list_url, item_id, fields) Patch fields on an existing List item. Only keys present in fields are changed.
sp_delete_item(list_url, item_id) Delete a List item — sends to recycle bin (recoverable for ~93 days).
sp_share_create(url, type="view", scope="organization", expires?, password?) Create a sharing link. Conservative defaults: type="view", scope="organization". The agent must explicitly pass scope="anonymous" to make a public link — that's the most common ISMS-audit finding, so we don't make it the default. type="edit" grants WRITE to anyone with the URL within scope.
sp_share_revoke(url, link_id) Revoke (delete) a sharing-link permission. After this call the share URL stops working. link_id comes from sp_share_create or sp_share_list.
sp_page_update(page_url, title?, description?, thumbnail_web_url?) Update a SharePoint Page's metadata. Pass only the fields you want to change. Canvas-layout (web-parts) edits are NOT supported in v0.3 — round-tripping the deep nested JSON safely needs more design work; deferred to a follow-up.

Recycle bin: list-only, beta endpoint

sp_trash_list calls Microsoft Graph's /beta endpoint. The site-level recycle-bin listing has not yet been promoted to v1.0; the beta endpoint is stable enough that SharePoint's own web UI / admin center rely on it, but the schema can change. We pin to the documented shape and will migrate to v1.0 when it lands.

Restore is not implemented. Microsoft Graph doesn't currently expose a /restore action for site-recycle-bin items (only on SharePoint Embedded fileStorageContainer recycle bins). Use the SharePoint web UI to restore individual items; we'll add sp_trash_restore once Microsoft surfaces the action or we add a SharePoint REST API fallback.

Large files

sp_save uses Microsoft Graph's resumable upload session for files larger than 100 MB (configurable via SP_CHUNKED_UPLOAD_THRESHOLD_MB). Files at-or-below the threshold use a single-shot PUT /content for a faster path. Microsoft caps single-shot at 250 MB; the resumable path supports up to 250 GB. Chunks are 5 MiB and retry on transient 5xx / connection errors with exponential backoff.

Authentication

  • OAuth 2.0 Device Code flow against Microsoft Identity (default). You sign in once; the refresh token is cached locally and silently renewed (~60–90 days until full re-login).
  • Bring-your-own-app or use ours. XMV publishes a multi-tenant Entra app registration that's baked in as the default — same pattern as Azure CLI / GitHub CLI. Tenants with strict app-allowlisting can override via SP_CLIENT_ID and SP_TENANT_ID env vars.
  • Token storage is auto-detected at first use: OS keyring (macOS Keychain / Windows Credential Locker / Linux Secret Service) when available, mode-0600 plain JSON file as fallback (same convention as gh auth, aws configure). Optional encryption with SP_TOKEN_PASSPHRASE for paranoid setups or CI.
  • Multi-customer / multi-tenant: separate SP_PROFILE per tenant, each with its own token cache.

Login from an MCP client (recommended for AI-mediated workflows)

The agent can drive sign-in directly via two MCP tools — no terminal shell-out required:

  1. Agent calls sp_login_status first. If status == "signed_in", just proceed; the user is already authenticated.
  2. Otherwise calls sp_login_begin, which returns immediately with a user_code and verification_url. The agent surfaces these to the user and polls sp_login_status until status flips to signed_in (or to a terminal expired / failed).

The user-facing chat output should look like:

CCQ8U66HZ

https://login.microsoft.com/devicelogin

Code first in its own code block (so long-press copy yields just the code, no labels), URL second on its own line as a plain auto-link (so it's tappable on mobile). The user copies the code, taps the link, pastes into the page that opens — minimum app-switching. The MCP tool's description tells the agent this; agents that follow it produce a clean mobile UX.

Limitation: pending sessions live in the MCP server process. If the server restarts mid-flow (Claude Code session ends, container redeployed) before the user enters the code, the session is lost — the agent must call sp_login_begin again. Persisting the asyncio polling task across restarts is non-trivial and deferred; if you hit this, file an issue.

Manual fallback: CLI

For terminal use or scripting, the original CLI subcommands still work:

uvx mcp-server-sharepoint login --profile <name>
uvx mcp-server-sharepoint logout --profile <name>

Both write to the same token cache sp_login_begin does — you can sign in via CLI once, then the MCP server uses the cached token without ever hitting sp_login_begin.

Service-principal mode (unattended automation)

For CI / scheduled jobs where no human is in the loop, run with SP_AUTH_MODE=service-principal (or just set SP_CLIENT_SECRET — auto-detected). Required env vars: SP_CLIENT_ID, SP_CLIENT_SECRET, SP_TENANT_ID. The app registration must have Application Microsoft Graph permissions (Files.ReadWrite.All, Sites.ReadWrite.All) with admin consent recorded.

Tradeoff: every action is attributed to the application principal in SharePoint's audit log, NOT a real user. The compliance-friendly default stays delegated user auth — only switch when no human is in the loop.

Security model

Three layers of "don't accidentally damage anything":

  1. Your MCP client (Claude Code) prompts before each tool call by default. Read tools are flagged read-only; write tools are flagged destructive — you see the difference at the prompt.
  2. Read-only by default at our server. Without SP_ALLOW_WRITES=true, the write tools aren't even registered. The agent literally can't see them.
  3. sp_save requires a non-empty audit comment. The agent has to articulate intent, and that lands in the SharePoint audit log.

The threat model is "your local OS account is trusted" — same as ~/.ssh/id_rsa, gh tokens, aws config. The tool isn't designed to defend against host compromise; it's designed to keep audit trails honest under normal use.

Roadmap

Version Status Theme Highlights
v0.1 ✅ released 2026-05-07 Audit-preserving doc edits The seven sp_* tools above, three-layer test harness, Trusted-Publisher PyPI release pipeline, branch-protected main.
v0.2 ✅ released 2026-05-07 Write-side polish sp_publish (upload new file), sp_history + sp_get_version (version-history access), sp_open_many + sp_save_many (bulk operations with concurrency cap), sp_status(verify=True) server-side reconciliation, resumable uploads for files >100 MB (auto-switch), service-principal auth for unattended automation.
v0.3 ✅ released 2026-05-07 Broader SharePoint surface Site discovery (sp_sites / sp_subsites / sp_followed_sites), multi-library support + sp_drives, SharePoint Lists CRUD, recycle-bin listing (sp_trash_list), permissions inspection (sp_permissions), sharing-link create/list/revoke (sp_share_*), modern Pages read/update (sp_pages_list / sp_page_read / sp_page_update), Graph delta-query change tracking (sp_changes).
v0.4 🤔 maybe Admin functions Site / library / permission administration, IF customer demand emerges.
v1.0 🎯 stability lock-in "API stable, production-tested" After v0.x has been used in real customer environments for ~3–6 months without breaking changes. Not "more features" — a commitment that what you depend on today still works tomorrow.

The full ticket-by-ticket plan lives at the issues page.

Multi-profile pattern

For consultancy workflows with multiple SharePoint tenants, give each its own profile so the token caches don't collide:

{
  "mcpServers": {
    "sharepoint-acme": {
      "command": "uvx",
      "args": ["mcp-server-sharepoint"],
      "env": { "SP_PROFILE": "acme" }
    },
    "sharepoint-globex": {
      "command": "uvx",
      "args": ["mcp-server-sharepoint"],
      "env": { "SP_PROFILE": "globex" }
    }
  }
}

Sign each one in separately:

uvx mcp-server-sharepoint login --profile acme
uvx mcp-server-sharepoint login --profile globex

Tools appear in Claude as mcp__sharepoint-acme__sp_search etc. Cross-tenant accidents don't happen because the tokens are namespaced.

BYO Entra app registration

Tenants with strict app-allowlisting can override the bundled multi-tenant default:

{
  "mcpServers": {
    "sharepoint": {
      "command": "uvx",
      "args": ["mcp-server-sharepoint"],
      "env": {
        "SP_TENANT_ID": "<your-tenant-guid>",
        "SP_CLIENT_ID": "<your-app-registration-guid>"
      }
    }
  }
}

The app registration must be: multi-tenant or single-tenant, public client (no secret), Device Code flow allowed, with delegated permissions Files.ReadWrite.All, Sites.ReadWrite.All, User.Read, offline_access.

Token storage

Three backends, auto-detected at first use:

Tier Backend When Setup
1 OS keyring macOS Keychain / Windows Credential Locker / Linux with Secret Service none
2 Plain file ~/.cache/sharepoint-mcp/<profile>/token.json mode 0600 Headless Linux default none
3 Encrypted file (Fernet, Scrypt KDF) When SP_TOKEN_PASSPHRASE is set env var

Force a specific backend with SP_TOKEN_STORE=keyring|file|encrypted-file. See the spike doc for the rationale — short version: same security model as gh auth, aws configure, npm login.

Troubleshooting

"No usable credentials"

The cached token expired (refresh tokens last ~60–90 days) or never existed. Run:

uvx mcp-server-sharepoint login --profile <name>

"Cannot checkout: file is already checked out by another user"

Someone else (or a previous instance of your own agent) has the file locked. Wait, or in the SharePoint web UI go to the library → file → "Discard check-out".

"File changed under us between sp_open and sp_save"

Your agent had the file open, but someone else edited it before your save. Recover with:

sp_release(url)        # drop your stale working copy + lock
sp_open(url)           # acquire fresh lock + content
# re-apply edits to the new content
sp_save(url, comment="…", version="minor")

Linux: keyring fails / "Secret Service unavailable"

The plain-file backend kicks in automatically — no action needed. If you'd rather have encryption at rest:

export SP_TOKEN_PASSPHRASE='<some-strong-passphrase>'
uvx mcp-server-sharepoint login --profile <name>

Recovery after a crash

uvx mcp-server-sharepoint     # restart the server

In the agent, ask sp_status — you'll see anything that was checked out before the crash. For each, either resume work (working file is still on disk; sp_save works as normal) or drop it (sp_release).

The registry survives crashes; nothing is lost.

Development

git clone https://github.com/XMV-Solutions-GmbH/sharepoint-mcp.git
cd sharepoint-mcp
uv sync --extra dev

# Unit + integration (no real SharePoint), with coverage reporting
./tests/run_tests.sh

# Harness (real SharePoint sandbox; requires harness-profile login)
./tests/run_tests.sh harness

Renewing the harness token

The CI harness job authenticates via a refresh token stored as the GitHub repo secret SHAREPOINT_HARNESS_TOKEN_JSON. Microsoft Identity rotates refresh tokens roughly every 60-90 days, so this is a recurring monthly maintenance chore for the maintainer.

A one-command script handles the whole flow — Device Code login, /me smoke test, base64-encoding the cached token, gh secret set against the repo:

./scripts/renew-harness-token.sh

Walks through the Microsoft Device Code prompt, then uploads the new token to GitHub. After it finishes, CI's next harness run picks up the fresh token automatically. No other manual steps.

Document What's in it
docs/app-concept.md Vision, MVP scope, MCP tool surface, auth, conflict model
docs/testconcept.md Three-layer test strategy (unit / integration / harness)
docs/RELEASING.md How releases happen
ENGINEERING_PRINCIPLES.md Project-agnostic engineering baseline
CLAUDE.md Project-specific overrides
docs/spikes/ Design-decision history (httpx vs SDK, token storage, etc.)

Contributing

Contributions are welcome. Please read CONTRIBUTING.md and the Code of Conduct first.

Bug reports and feature requests go to GitHub Issues.

Licence

Dual-licensed under either of:

at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this project by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Contact

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mcp_server_sharepoint-0.5.0.tar.gz (281.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mcp_server_sharepoint-0.5.0-py3-none-any.whl (99.0 kB view details)

Uploaded Python 3

File details

Details for the file mcp_server_sharepoint-0.5.0.tar.gz.

File metadata

  • Download URL: mcp_server_sharepoint-0.5.0.tar.gz
  • Upload date:
  • Size: 281.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.13 {"installer":{"name":"uv","version":"0.11.13","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for mcp_server_sharepoint-0.5.0.tar.gz
Algorithm Hash digest
SHA256 ca73d4245f238dde1e8526d00847e8f0de0cdfe4d185d2ffd205e7d763c0aa28
MD5 b2d5ea097118edabc5437d457a81752c
BLAKE2b-256 9c866dfa506e3f001f67796812a4481e05ab8e568d66386ba69e2c84881e7058

See more details on using hashes here.

File details

Details for the file mcp_server_sharepoint-0.5.0-py3-none-any.whl.

File metadata

  • Download URL: mcp_server_sharepoint-0.5.0-py3-none-any.whl
  • Upload date:
  • Size: 99.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.13 {"installer":{"name":"uv","version":"0.11.13","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for mcp_server_sharepoint-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3772c04ff3992f951f2caa4026ceea6205b2fac9fbe50cf22aead609e32fb7b7
MD5 8f4f86406d02768b2cda04bdcf508caa
BLAKE2b-256 f298ed4e3eb4ff643df163ca5c727221e4fcf8f983ef37af6a3f54e376a0e4c9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page