Skip to main content
Glama
README.md
# Matter Desk: a read-only MCP connector for Microsoft 365 matter files

[![ci](https://github.com/dojedaro/graph-matter-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/dojedaro/graph-matter-mcp/actions/workflows/ci.yml)

Matter Desk is an MCP (Model Context Protocol) server that lets Claude work over one user's
Microsoft 365 documents, mail and calendar through Microsoft Graph. It is read-only by
design, every call is written to an audit log, and answers are meant to cite a document and
paragraph or an email subject and date. It ships with two Claude Code skills for
dispute-style work (a dated chronology, and an issue summary that abstains when the files do
not say) and with a synthetic sample matter so you can try everything with no Microsoft
account.

## What this proves

- An MCP server can expose a matter's OneDrive files, mail and calendar to Claude with no write
  path: read-only scopes, a GET-only client, no write tools, and a hook that blocks write calls.
- Every call is audited (redacted arguments, no content, hash-chained) and document tools can
  be confined to one matter folder.
- Answers can be cited to a document and paragraph: numbering is stable and checked against
  ground truth for .docx, .pdf and .txt files on the project's own generated sample files.
- Packaged as a Claude Code plugin (manifests pass `claude plugin validate`); the MCP server runs end to end over stdio in mock mode (tested); the skills have not been run in a graded Claude session.
- The live Graph HTTP client parses the response shapes Microsoft documents for each endpoint
  it calls, and handles the documented error cases (see
  [Checked against Microsoft's documented Graph responses](#checked-against-microsofts-documented-graph-responses)).
- It does **not** prove behaviour against a real Microsoft account or answer quality; neither
  was measured.

**Status:** mock mode is tested and evaluated. **Live mode has never been run against a real Microsoft account**: that needs an Entra app registration, which requires a tenant I don't have. Instead, the live client is contract-tested against Microsoft's documented responses ([details](#checked-against-microsofts-documented-graph-responses)).
See [Limitations](#limitations) and [What was and was not measured](#what-was-and-was-not-measured).

All sample data is synthetic: invented companies, people and a fictional court claim number.
Every sample file, email and event says so.

## Quickstart (mock mode, no Microsoft account)

Activate the virtual environment **before launching `claude`**: `.mcp.json` runs
`python -m matter_desk.server`, so `python` must resolve to the environment where the package
is installed.

```bash
python -m venv .venv && source .venv/bin/activate      # Windows: .venv\Scripts\activate
pip install -e ".[dev]" && pytest -q && python eval/run_eval.py
```

To use it from Claude Code, run `claude` in this folder and approve the project MCP server
`matter-desk` from `.mcp.json` (it starts in `MATTER_DESK_MODE=mock`). Then try the skills:

- `/chronology build a chronology of the Aldermere v Vessey matter in MatterDesk-Sample`
- `/issue-summary what do the files say about whether the Helmsford letter was disclosed?`
- `/issue-summary what do the files say about a Serious Fraud Office referral?` (should
  abstain: nothing in the sample mentions it)

### What the tools return (real mock-mode output, no LLM)

Tool calls a chronology-style session would make, run directly against the mock backend on the
synthetic sample matter. Inputs and outputs only (outputs trimmed); no model is involved, and
this is mock data, not Microsoft Graph.

```
> search_documents({"query": "Helmsford letter", "top": 2})
  05_Helmsford_Letter_2022-04-11.docx          /MatterDesk-Sample/Correspondence/...
  09_Response_to_Letter_Before_Claim.docx      /MatterDesk-Sample/Pleadings/...
> read_document({"item_id": "01MATTERDESK0005"})
  05_Helmsford_Letter_2022-04-11.docx | paragraphs: 7
  [2] Helmsford Automotive Ltd: letter to Corvane Components Ltd
  [3] Dated 11 April 2022. Stamped received by Vessey Trading Group Ltd on 13 April 2022.
> search_mail({"query": "Helmsford", "top": 2})
  "Helmsford letter found in shared mailbox"   2022-10-12T16:22:00Z
  "Note of Brenner interview"                  2023-09-12T18:10:00Z
```

### Install as a Claude Code plugin

The repository is also a plugin marketplace containing one plugin, `matter-desk` (MCP server,
the two skills and the write-blocking hook). Install the Python package (`pip install .`) into
the environment Claude Code will use, then:

```
/plugin marketplace add dojedaro/graph-matter-mcp
/plugin install matter-desk@matter-desk-marketplace
```

(Local path form: `/plugin marketplace add /path/to/graph-matter-mcp`.) `claude plugin
validate .` passes on the manifests; I have not installed it from a marketplace end to end.
The plugin does not install Python dependencies for you, and its server starts in mock mode.
Plugin-provided tools are named `mcp__plugin_matter-desk_matter-desk__*`; the hook handles that
prefix.

The server needs Python 3.11 or later. It pins `mcp<2` because the FastMCP API was renamed in
the 2.x series of the Python SDK.

## Live setup (real Microsoft 365)

Follow [docs/SETUP.md](docs/SETUP.md): Entra app registration (public client, device code,
read-only delegated permissions), environment variables, one-time `matter-desk-login`, and an
optional script that seeds the sample documents into a `MatterDesk-Sample` folder on your own
OneDrive.

## Architecture

```mermaid
flowchart LR
    C[Claude Code / MCP client] -- stdio JSON-RPC --> S[Matter Desk MCP server]
    H[PreToolUse hook<br/>blocks write calls] -. guards .-> C
    S --> T[Tools: validate, cap, audit]
    T --> G[GraphClient<br/>GET only, retry 429/5xx]
    T --> A[(audit.jsonl<br/>hash-chained)]
    G -- live mode --> M[Microsoft Graph<br/>OneDrive, Outlook, Calendar]
    G -- mock mode --> F[In-process fake Graph<br/>synthetic matter, BM25 search]
    L[matter-desk-login<br/>MSAL device code] --> K[(token cache<br/>~/.matter_desk, outside repo)]
    K --> G
```

## Tools

| Tool | Graph endpoint | Returns | Limits |
|---|---|---|---|
| `search_documents(query, top)` | `GET /me/drive/root/search(q='...')` | id, name, type, path (null when Graph omits it), webUrl, lastModified | query 1-200 chars; top 1-25 (default 10) |
| `read_document(item_id, start_paragraph)` | `GET /me/drive/items/{id}` then `/content` | text with `[n]` paragraph numbers, paragraph count, pages (PDF), truncation flag | .docx/.pdf/.txt only; 10 MB download cap; 40,000 chars per call, cut at a paragraph boundary with `next_start_paragraph` |
| `list_folder(path)` | `GET /me/drive/root:/{path}:/children` | files and folders at a path | path validated (no `..`, no `:`); 100 items |
| `search_mail(query, top)` | `GET /me/messages?$search=` | id, subject, from, date, 255-char preview | as `search_documents` |
| `get_message(message_id)` | `GET /me/messages/{id}` | subject, from/to/cc, date, plain-text body | body capped at 20,000 chars |
| `list_events(start, end)` | `GET /me/calendarView` | subject, start/end (UTC), location, attendees, preview | ISO 8601 dates; range at most 366 days; 50 events |

Errors are returned as readable messages: 401 (sign in again), 403 (permission), 404, 429
(retried using `Retry-After`, capped at 30 s per wait and 3 retries, then reported), 5xx
(retried with exponential backoff).

Paragraph numbering rule (also in `matter_desk/extract.py`): `.txt` blocks split on blank
lines; `.docx` non-empty paragraphs in body order, with table cells in order; `.pdf` blocks are
inferred from vertical spacing and joined across page breaks when a paragraph ends without
punctuation. The PDF rule is a heuristic and will not match a human reader on every layout
(columns, footnotes, scanned images). Scanned PDFs return an error.

## Checked against Microsoft's documented Graph responses

A live run needs an Entra app registration, and I have no Entra tenant (a personal Microsoft
account cannot register an app without one), so there has been none. The next-best evidence is a contract-test layer
(`tests/test_graph_contract.py`): the same `GraphClient` and tools used in live mode, with a
fixed fake token passed in through the constructor (no environment flag, no bypass in
production code), run against an `httpx.MockTransport` that serves response bodies taken from
the Microsoft Learn Graph v1.0 reference. Each fixture in `tests/fixtures/graph_docs/` records
its source URL, retrieval date (2026-12-03) and whether the body is **verbatim** or **composed**
by this project (the docs give no full file item, no `$search` message example and a truncated
`calendarView` example, so those are marked composed).

Endpoints covered: drive search, driveItem get, driveItem content (302 to a download URL),
list children, list messages, get message, calendarView.

What it checks:

- The documented shapes parse: names, ids, `webUrl`, dates, message sender/recipients and text
  or HTML bodies, event start/end with time zone, attendees. Fields the docs leave out
  (`parentReference.path`, `webUrl`, `from`, `id` in children) come out as null, not as errors.
- The `/content` 302 is followed and the bearer token is **not** sent to the download host.
- Errors from the Graph "error responses" and throttling pages: 429 with `Retry-After` in
  seconds (and as an HTTP-date, which Graph does not document but HTTP allows), a 30 s cap,
  retry counts (4 requests, 3 waits), 503 with and without `Retry-After`, 401 (expired token,
  one request, no retry, points to `matter-desk-login`) and 403 (names the delegated permission
  the failing call needs, passes Graph's error code through).
- The requested scopes against the least-privilege table on each endpoint's doc page, in
  [docs/PERMISSIONS.md](docs/PERMISSIONS.md). `Files.Read` is exactly least privilege.
  `Mail.Read` is above the documented `Mail.ReadBasic` on purpose (ReadBasic excludes bodies and
  previews). `Calendars.Read` may be above `Calendars.ReadBasic` and `User.Read` is not needed by
  any data call; both are recorded, not changed. The scopes are documented as available for
  personal accounts.

What it does **not** prove: anything about a real tenant or account; real search ranking; real
OneDrive indexing or how fresh it is; whether the live service returns exactly what the docs
show (the docs examples are shortened, and 401/403/503 bodies are composed in the documented
envelope, not quoted); whether `Calendars.ReadBasic` would be enough; network behaviour
(latency, TLS, proxies, real throttling thresholds); the device-code sign-in itself.

## Security design

- **Read-only scopes.** The app registration needs only delegated `Files.Read`, `Mail.Read`,
  `Calendars.Read`, `User.Read` and `offline_access`. No tool can write, and `GraphClient`
  raises on any method other than GET.
- **Scope guard.** On every token use the server checks the granted scopes (the MSAL result,
  and the `scp` claim when the access token is a readable JWT; no signature check) and refuses
  to run if any contains `ReadWrite`, `Send`, `.Write` or `.All`. Use a separate registration for
  the optional seed script (docs/SETUP.md section 7): removing a permission from a registration
  does not revoke consent already given, so a registration must never hold a write scope.
- **Matter-folder scoping.** Set `MATTER_DESK_ROOT=/MatterDesk-Sample` (the `.mcp.json` default)
  and `search_documents`, `list_folder` and `read_document` cannot leave that folder. Search
  runs against the folder endpoint, hits with a path outside are dropped, and `read_document`
  re-checks the item's location (failing closed if Graph gives no path). This is an
  ethical-wall style, client-side folder scoping for documents only: it is configuration, not
  an access-control system, and mail and calendar are not scoped.
- **Hook as a second layer.** `.claude/settings.json` attaches `hooks/block_graph_writes.py`
  as a `PreToolUse` hook for MCP tools and shell tools. It blocks any non-read matter-desk
  tool, write-verb tools on other Microsoft 365 MCP servers, and shell commands that call
  Microsoft Graph with a write method or write cmdlet. It fails closed on unparseable input, and its launcher (`hooks/run_hook.sh`) blocks if no
  Python interpreter works or the hook crashes. It is a pattern check, not a sandbox: an
  obfuscated command can evade it, and it does not inspect scripts that are run from files.
  The read-only scopes are the real boundary.
- **Audit log.** Every tool call appends one JSON line (timestamp, tool, arguments with
  secrets redacted, result count, latency, status). Document text and mail bodies are never
  logged. Lines are hash-chained, so an edited or deleted line is detectable with
  `verify_chain`. It is append-only in the sense that the code only appends; it is not
  write-once storage, and the arguments (search queries) can themselves be sensitive, so
  protect the file. Default path `~/.matter_desk/audit.jsonl`.
- **Token cache outside the repo.** `~/.matter_desk/token_cache.bin`, encrypted through
  `msal-extensions` where the OS supports it, otherwise a plain file (`token_cache.plain.json`, owner-only permissions) with a logged
  warning.
  `.env`, token caches and audit logs are git-ignored.
- **Data flow.** Content fetched from Microsoft Graph goes to the MCP client (Claude) and
  nowhere else; the server has no other network destination besides Microsoft login and
  Graph. Whatever Claude receives is handled under your Claude deployment's terms, which is
  a separate decision for any real client matter.
- **Prompt injection.** Document and email text is untrusted input. The skills tell Claude to
  ignore instructions found in files, and the tools cannot write, but a malicious document
  could still try to steer what Claude says. Review outputs.
- **Input validation.** Item ids, paths, dates and query lengths are validated before any
  request is made.

## Evaluation

Everything below is generated by `python eval/run_eval.py` (results in `eval/results/*.json`)
and written into this README by `scripts/render_results_table.py`. No number here is typed by
hand, and a test fails if the table and the JSON files disagree.

What it measures, with no LLM and no paid API: whether `search_documents` / `search_mail`
return the expected source in the top 1, 3 and 5; whether the paragraph number `read_document`
gives the evidence phrase equals the number in the generator's manifest (written independently
of the extractor); and tool latency. The golden set is `eval/golden.jsonl` (32 questions over
the sample matter: 21 document, 6 mail, 2 calendar, 3 abstention probes).

<!-- EVAL-TABLE:START -->
Run: `mock` mode, 32 golden questions (21 doc, 6 mail, 2 event, 3 negative), search engine: mock BM25 (keyword), generated 2026-12-03T04:06:25+00:00, Python 3.14.2.

| Measure | n | recall@1 | recall@3 | recall@5 | MRR |
|---|---|---|---|---|---|
| search_documents, keyword query | 21 | 90% | 100% | 100% | 0.95 |
| search_documents, raw question text | 21 | 76% | 95% | 95% | 0.85 |
| search_mail, keyword query | 6 | 100% | 100% | 100% | 1.00 |
| search_mail, raw question text | 6 | 83% | 100% | 100% | 0.92 |

| Other measure | Result |
|---|---|
| Calendar: expected event inside `list_events` window | 100% (n=2) |
| Abstention probes: search returned nothing (keyword / raw question) | 0% / 0% (n=3) |
| Extraction fidelity: extracted paragraphs equal generator ground truth | 13/13 documents |
| Locator correctness: evidence phrase is at the ground-truth paragraph | 21/21 (docx 12/12, pdf 7/7, txt 2/2) |


In-process tool latency in this run (varies by machine and run, so these will not reproduce exactly): median 1.02 ms for `search_documents`, 10.51 ms for `read_document`; the first `search_documents` call took 384.96 ms because it builds the index.
<!-- EVAL-TABLE:END -->

How to read this:

- **Search here is a mock.** Mock mode ranks with a small BM25 keyword scorer
  (`matter_desk/search.py`: lowercase tokens, a short stop-word list, no stemming or
  synonyms; any matching token scores). Microsoft Graph's search ranks differently. These
  retrieval numbers describe the mock, not Microsoft Graph. A live run is separate:
  `python eval/run_eval.py --mode live` after seeding (see docs/SETUP.md). It has not been run.
- **Small and easy.** The corpus is 13 documents and 16 emails, so recall@5 on documents has a
  chance level of about 38% (5 of 13). The keyword queries were written by the same person who
  wrote the corpus, so they are friendlier than real user queries; the raw-question rows are
  closer to a model that does not rephrase. Treat the numbers as a regression check for the
  tools, not as evidence about legal-search quality.
- **Abstention probes return results.** BM25 with any-term matching returns something when
  one query word occurs anywhere (for example "fraud" in "Serious Fraud Office"), so 0% of
  the probes returned nothing. This is expected for keyword search and is why abstention is
  the skills' job (judge relevance, say "the files do not address this"), not the search
  tool's. Whether Claude actually abstains is **not measured**.
- **Locator correctness** checks that the numbering is consistent between the generator's
  intended paragraphs and the extracted ones for .docx, .pdf and .txt files that the
  generator itself produced. It is not a test on third-party PDFs.
- **Latency** is in-process code time (validation, ranking, extraction, audit write), not
  network or Graph time, and it varies per run.

### What was and was not measured

Measured (mock mode): tool-level retrieval, citation-locator consistency, extraction
fidelity, tool latency, plus the unit and integration test suite (including a real stdio MCP
session in mock mode).

Not measured:

- End-to-end answer quality with Claude (chronology correctness, citation accuracy of
  generated answers, abstention behaviour). That needs a Claude API key or interactive
  sessions, which this project deliberately did not use. To measure it later: for each golden
  question, run Claude with the six tools and no other context, record its answer and the
  tool calls, then grade (a) whether the cited document and paragraph match the gold evidence
  and (b) whether the abstention probes are answered with an abstention. Grade with a human
  or a separate model, and report the grader.
- Live Microsoft Graph behaviour: authentication, real search ranking, real throttling
  thresholds, the shape of real responses (the mock was written from the documentation, and
  the live client was then checked against the documented examples, which are shortened),
  SharePoint, large files.
- The token cache encryption path on macOS and Linux.

## Limitations

- Synthetic data only. Nothing here has been tried on a real client file.
- Mock search is a keyword ranker (see above); live ranking is unknown until run.
- Personal accounts versus work tenants: the device code flow works for both when the app
  registration allows both account types, but work tenants may block device code with
  Conditional Access or require admin consent. Personal accounts have no SharePoint sites.
  `consumers`/`organizations`/tenant-id selection is by `MATTER_DESK_TENANT`.
- SharePoint sites and other people's files need `Files.Read.All` / `Sites.Read.All`, which
  this project does not request. Only the signed-in user's own OneDrive and mailbox are in
  scope. Shared mailboxes are not covered.
- Mail search uses Graph's `$search` on `/me/messages`, which returns at most the first page
  and cannot be combined with ordering. Attachments are not read.
- PDF paragraph detection is heuristic; scanned PDFs, old `.doc`, `.xlsx`, and `.msg` are
  unsupported.
- The audit log is tamper-evident, not tamper-proof. There is no server-side per-matter access
  control: `MATTER_DESK_ROOT` confines document tools to one folder by client-side
  configuration only; mail and calendar are unscoped, and the connector can otherwise see
  whatever the signed-in user can see.
- The hook is a best-effort pattern check; it does not inspect scripts run from files.
- Under `MATTER_DESK_ROOT`, a live item whose `parentReference.path` Graph does not return
  cannot be read (fail closed). Search hits without a path are kept only because the scoped
  endpoint returned them. This has not been checked against real Graph.
- No LLM-graded answer quality (see above).
- The seed script uploads documents only (not mail or calendar items) and needs a temporary
  write scope.

## Repository layout

```
matter_desk/        server, tools, Graph client, auth, audit, extraction, mock backend
  sample_data/      generated synthetic matter (13 files, 16 emails, 6 events, manifest)
scripts/            generate_sample_data.py, seed_onedrive.py, render_results_table.py
hooks/              block_graph_writes.py, run_hook.sh (fail-closed launcher), hooks.json (plugin)
skills/             plugin copies of the two skills (identical to .claude/skills; a test checks)
.claude-plugin/     plugin.json, marketplace.json
.claude/            settings.json (hook wiring), skills/chronology, skills/issue-summary
.mcp.json           registers the server for Claude Code (mock mode by default)
eval/               golden.jsonl, run_eval.py, score.py, results/
tests/              pytest suite
docs/SETUP.md       Entra app registration and live setup
docs/PERMISSIONS.md requested scopes versus the documented least privilege per endpoint
.github/workflows/  CI: ruff, pytest, mock-mode evaluation
```

Regenerate the sample data with `python scripts/generate_sample_data.py`; a test checks that
the committed data equals what the script produces.

## Development

```bash
pytest -q
ruff check . && ruff format --check .
python eval/run_eval.py && python scripts/render_results_table.py
```

Licence: MIT (see LICENSE).