Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ jobs:
with:
python-version: ${{ matrix.python-version }}
- run: uv sync --all-extras
- run: uv run ruff check src/ tests/
- run: uv run ruff check src/ tests/ scripts/
# `ruff check` passing says nothing about formatting: a separate tool with
# a separate verdict. With nothing running this, 49 of 105 files had
# drifted from the documented formatter (#78).
- run: uv run ruff format --check src/ tests/ scripts/
- run: uv run pytest --cov=outlook_mcp -v

# Guards the failure mode that shipped 1.12.0 and 1.13.0 broken for five weeks:
Expand Down
3 changes: 2 additions & 1 deletion .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ jobs:
run: |
uv sync --all-extras
uv run pytest -q
uv run ruff check src/ tests/
uv run ruff check src/ tests/ scripts/
uv run ruff format --check src/ tests/ scripts/

- name: Build
run: uv build
Expand Down
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,17 @@ this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm

## [Unreleased]

### Changed

- **The tree is formatted with `ruff format`, and CI enforces it.** The command was documented
in `CLAUDE.md` and the README but nothing enforced it, so following it rewrote 49 of 105 files
and then failed `ruff check` (#78). Every file under `src/`, `tests/` and `scripts/` is
now formatted, and `ci.yml`'s `test` job and `publish.yml` run
`ruff format --check src/ tests/ scripts/` beside `ruff check`, which also covers `scripts/`
now. Contributors: run `uv run ruff format src/ tests/ scripts/` before pushing.
The dev extra and the dependency group both require `ruff>=0.15.10,<0.17`, so a `pip install
outlook-graph-mcp[dev]` gets a ruff that formats the tree the way CI checks it.

### Security

- **The agent is told that mailbox content is not instructions.** Mail, events, contacts and
Expand Down
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ Works with any MCP client (OpenClaw, Claude Code, Cursor).
- `uv run pytest` — run tests (offline unit suite; `integration`/`live` markers are deselected by default)
- `uv run pytest -m live -v` — live query-shape guards; run before tagging if you changed any `$filter`/`$orderby`/`$search` construction (see `RELEASING.md` 1b)
- `uv run pytest -m integration -v` — live response-shape smoke tests
- `uv run ruff check src/ tests/` — lint
- `uv run ruff format src/ tests/` — format
- `uv run ruff check src/ tests/ scripts/` — lint
- `uv run ruff format src/ tests/ scripts/` — format (CI runs `ruff format --check` on the same paths and fails on any file it would change)
- `uv run outlook-mcp` — start server (stdio)
- `uv run python scripts/preflight.py` — pre-release Graph smoke test (must pass before tagging; see `RELEASING.md`)

Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -611,10 +611,10 @@ uv sync --extra dev
uv run pytest

# Lint
uv run ruff check src/ tests/
uv run ruff check src/ tests/ scripts/

# Format
uv run ruff format src/ tests/
# Format (CI fails if `ruff format --check` would change a file)
uv run ruff format src/ tests/ scripts/

# Run server locally (stdio)
uv run outlook-mcp
Expand Down
3 changes: 2 additions & 1 deletion RELEASING.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ Double-gated on purpose: the marker is deselected by default **and** the tier sk

```bash
uv run pytest --tb=no -q
uv run ruff check src/ tests/
uv run ruff check src/ tests/ scripts/
uv run ruff format --check src/ tests/ scripts/
```

The default run is the offline unit suite only — `addopts` deselects the `integration`, `live` and `live_write` markers, so this needs no network or token. Expect zero failures; the deselected count is those three tiers, and grows as they do.
Expand Down
11 changes: 9 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,13 @@ dev = [
"pytest>=8.0",
"pytest-asyncio>=0.24",
"pytest-cov>=5.0",
"ruff>=0.4",
# The same range in both places: CI fails any file `ruff format` would change,
# so the formatter version is part of the contract. 0.15 and 0.16 format this
# tree identically (0.8 and older reformat 7 files). Ruff changes its stable
# style, and can add rules to the selected sets, only in minor releases: lift
# the cap once the next minor passes `ruff format --check` and `ruff check`
# on src/ tests/ scripts/ (#78).
"ruff>=0.15.10,<0.17",
]

[project.scripts]
Expand Down Expand Up @@ -100,5 +106,6 @@ markers = [
dev = [
"pytest>=9.0.3",
"pytest-asyncio>=1.3.0",
"ruff>=0.15.10",
# Same range as the dev extra above, and for the same reason.
"ruff>=0.15.10,<0.17",
]
25 changes: 12 additions & 13 deletions scripts/preflight.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,7 @@
("me/outlook/masterCategories", "Categories"),
("me/mailFolders/inbox/messages/delta", "Mail delta"),
(
"me/calendarView/delta?startDateTime=2026-05-21T00:00:00Z"
"&endDateTime=2026-05-28T00:00:00Z",
"me/calendarView/delta?startDateTime=2026-05-21T00:00:00Z&endDateTime=2026-05-28T00:00:00Z",
"Calendar delta",
),
("me/contacts/delta", "Contacts delta"),
Expand Down Expand Up @@ -165,11 +164,15 @@ def _todo_task_rows(headers: dict[str, str]) -> tuple[list[tuple[str, str]], lis
task_id, attachment_id = _task_with_attachment(headers, list_id)
except Exception as exc:
reason = f"could not provision a live task: {exc}"
return [], [
f"To Do checklist items ({reason})",
f"To Do task attachments ({reason})",
f"To Do attachment entity GET ({reason})",
], []
return (
[],
[
f"To Do checklist items ({reason})",
f"To Do task attachments ({reason})",
f"To Do attachment entity GET ({reason})",
],
[],
)
task_path = f"me/todo/lists/{list_id}/tasks/{task_id}"

rows.append((f"{task_path}/checklistItems?$top=1", "To Do checklist items"))
Expand All @@ -186,9 +189,7 @@ def _todo_task_rows(headers: dict[str, str]) -> tuple[list[tuple[str, str]], lis
# (contentBytes off the attachment entity), so it is probed directly and
# the body is checked — a 200 without contentBytes is the shape the
# download tool now refuses, and worth a loud line here.
status, body = _get_json(
f"{task_path}/attachments/{attachment_id}", headers, timeout=60
)
status, body = _get_json(f"{task_path}/attachments/{attachment_id}", headers, timeout=60)
verdict = classify(status) if status is not None else "FAIL"
has_bytes = isinstance(body, dict) and "contentBytes" in body
print(
Expand All @@ -205,9 +206,7 @@ def _todo_task_rows(headers: dict[str, str]) -> tuple[list[tuple[str, str]], lis
"genuinely non-empty, that is a finding, not a pass"
)
# Legacy raw route, no longer used by any tool — kept as an extra signal.
rows.append(
(f"{task_path}/attachments/{attachment_id}/$value", "To Do attachment $value")
)
rows.append((f"{task_path}/attachments/{attachment_id}/$value", "To Do attachment $value"))
return rows, not_probed, failures


Expand Down
12 changes: 6 additions & 6 deletions src/outlook_mcp/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,16 +147,16 @@ def cmd_logout() -> None:
"""Remove this instance's auth record; report what stays behind."""
auth = AuthManager(_load_config_or_exit())
if auth.logout()["record_removed"]:
print("Removed this instance's auth record "
f"({DEFAULT_CONFIG_DIR}/auth_record.json).")
print(f"Removed this instance's auth record ({DEFAULT_CONFIG_DIR}/auth_record.json).")
else:
print("No auth record was present for this instance.")
print("This server will ask for `outlook-mcp auth` again on next start.")
print()
print("The encrypted token cache the OS keeps for azure-identity "
"(Keychain item Microsoft.Developer.IdentityService on macOS, its")
print("equivalent on other systems) is shared across apps and left in "
"place; its tokens")
print(
"The encrypted token cache the OS keeps for azure-identity "
"(Keychain item Microsoft.Developer.IdentityService on macOS, its"
)
print("equivalent on other systems) is shared across apps and left in place; its tokens")
print("age out on their own.")


Expand Down
4 changes: 1 addition & 3 deletions src/outlook_mcp/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,9 +135,7 @@ def _warn_on_unknown_keys(cls, data: object) -> object:
return data
for key in data:
if key in _LEGACY_KEYS:
logger.warning(
"Config key %r ignored: %s.", key, _LEGACY_KEYS[key]
)
logger.warning("Config key %r ignored: %s.", key, _LEGACY_KEYS[key])
elif key not in cls.model_fields:
logger.warning(
"Unknown config key %r ignored — supported keys: %s.",
Expand Down
21 changes: 7 additions & 14 deletions src/outlook_mcp/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,10 +238,8 @@ class ConfigLoadError(OutlookMCPError):
def __init__(self, reason: Exception, config_dir: str):
super().__init__(
"config_load_failed",
f"The settings file could not be loaded ({reason}); the server "
"booted read-only.",
f"Fix {config_dir}/config.json and restart the server. "
f"{LEAVE_SETTINGS_TO_THE_USER}",
f"The settings file could not be loaded ({reason}); the server booted read-only.",
f"Fix {config_dir}/config.json and restart the server. {LEAVE_SETTINGS_TO_THE_USER}",
)


Expand Down Expand Up @@ -294,8 +292,7 @@ def __init__(self, source: str, url: str, resource: str):
)
else:
message = (
f"Refusing a cursor that is not a {resource} delta link (from {source}): "
f"{shown!r}."
f"Refusing a cursor that is not a {resource} delta link (from {source}): {shown!r}."
)
action = (
"A delta cursor only works with the tool that returned it. Discard this "
Expand Down Expand Up @@ -346,12 +343,9 @@ def __init__(self, message: str):
"re-read the item and send the update again."
),
(429, None): (
"Rate limited by Microsoft Graph. "
"Back off and retry; respect any Retry-After header."
),
(503, None): (
"Microsoft Graph is temporarily unavailable. Retry after a short delay."
"Rate limited by Microsoft Graph. Back off and retry; respect any Retry-After header."
),
(503, None): ("Microsoft Graph is temporarily unavailable. Retry after a short delay."),
}


Expand Down Expand Up @@ -388,14 +382,13 @@ def wrap_graph_error(exc: Exception) -> GraphAPIError:
from msgraph.generated.models.o_data_errors.o_data_error import (
ODataError as _ODataError,
)

graph_types: tuple[type, ...] = (APIError, _ODataError)
except ImportError: # pragma: no cover — defensive
graph_types = (APIError,)

if not isinstance(exc, graph_types):
raise TypeError(
f"wrap_graph_error: not a Graph SDK error: {type(exc).__name__}"
)
raise TypeError(f"wrap_graph_error: not a Graph SDK error: {type(exc).__name__}")

status_code: int | None = getattr(exc, "response_status_code", None)

Expand Down
8 changes: 2 additions & 6 deletions src/outlook_mcp/folder_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,12 @@ async def fetch_all_top_level_folders(graph_client: Any, top: int = 100) -> list
response = await graph_client.me.mail_folders.get(request_configuration=config)
collected = list(response.value) if response and response.value else []
while getattr(response, "odata_next_link", None):
response = await graph_client.me.mail_folders.with_url(
response.odata_next_link
).get()
response = await graph_client.me.mail_folders.with_url(response.odata_next_link).get()
collected.extend(list(response.value) if response and response.value else [])
return collected


async def fetch_all_child_folders(
graph_client: Any, parent_id: str, top: int = 100
) -> list[Any]:
async def fetch_all_child_folders(graph_client: Any, parent_id: str, top: int = 100) -> list[Any]:
"""Fetch every child folder of `parent_id`, following pagination."""
from msgraph.generated.users.item.mail_folders.item.child_folders import (
child_folders_request_builder as cf,
Expand Down
8 changes: 2 additions & 6 deletions src/outlook_mcp/throttle.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,7 @@ async def send_with_retry(
while True:
resp = await send(url, **call_kwargs)
if resp.status_code in _RETRYABLE and attempt < max_retries:
wait = parse_retry_after(
dict(resp.headers), default_backoff * (2**attempt)
)
wait = parse_retry_after(dict(resp.headers), default_backoff * (2**attempt))
await sleep(wait)
attempt += 1
continue
Expand Down Expand Up @@ -129,9 +127,7 @@ async def retry_throttled_subrequests(
continue # no response for this id; caller handles the gap
status = sub.get("status", 0)
if status in _RETRYABLE and attempt < max_retries:
wait = parse_retry_after(
sub.get("headers") or {}, default_backoff * (2**attempt)
)
wait = parse_retry_after(sub.get("headers") or {}, default_backoff * (2**attempt))
max_wait = max(max_wait, wait)
retry_next.append(req)
else:
Expand Down
6 changes: 2 additions & 4 deletions src/outlook_mcp/tools/_recurrence.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,7 @@ def _enum_lookup(enum_cls: Any, value: str, label: str) -> Any:
if "daysOfWeek" in pattern_in:
if not isinstance(pattern_in["daysOfWeek"], list):
raise ValueError(
"recurrence pattern.daysOfWeek must be a list of day names, "
'e.g. ["monday"]'
'recurrence pattern.daysOfWeek must be a list of day names, e.g. ["monday"]'
)
pattern.days_of_week = [
_enum_lookup(DayOfWeek, d, "pattern.daysOfWeek") for d in pattern_in["daysOfWeek"]
Expand Down Expand Up @@ -485,8 +484,7 @@ def shifted(day: Any) -> str:
kind,
old,
new,
"That crosses into a different month, which no single dayOfMonth "
"expresses.",
"That crosses into a different month, which no single dayOfMonth expresses.",
)
pattern["dayOfMonth"] = new.day
if kind == "absoluteYearly":
Expand Down
7 changes: 2 additions & 5 deletions src/outlook_mcp/tools/batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,17 +84,14 @@ async def batch_triage(
validate_graph_id(mid)

if action == "flag" and value not in _VALID_FLAG_STATUSES:
raise ValueError(
f"flag value must be one of {_VALID_FLAG_STATUSES}; got {value!r}"
)
raise ValueError(f"flag value must be one of {_VALID_FLAG_STATUSES}; got {value!r}")

resolved_value: Any = value
if action == "move":
resolved_value = await resolve_folder_id(graph_client, value)

subrequests = [
_build_subrequest(i, mid, action, resolved_value)
for i, mid in enumerate(message_ids)
_build_subrequest(i, mid, action, resolved_value) for i, mid in enumerate(message_ids)
]
batch_body = {"requests": subrequests}

Expand Down
4 changes: 2 additions & 2 deletions src/outlook_mcp/tools/calendar_write.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,7 @@ def _as_instant(date_time: str, projected_zone: str | None) -> str:
return text
return text + "Z"


# Spellings an agent plausibly emits for the two Graph values whose names don't
# match Outlook's own menu labels ("Out of office", "Working elsewhere"), mapped
# to the normalised form of the real value. Widening what we accept cannot break
Expand Down Expand Up @@ -671,8 +672,7 @@ async def update_event(
)
if remove_recurrence and recurrence is not None:
raise ValueError(
"Pass either recurrence or remove_recurrence, not both — they ask for "
"opposite things"
"Pass either recurrence or remove_recurrence, not both — they ask for opposite things"
)
if timezone is not None and (start is None or end is None):
raise ValueError(
Expand Down
Loading
Loading