msteams-mcp
by dataoracle
README.md
# msteams-mcp: Microsoft Teams MCP server
An MCP server that lets Claude (or any MCP client) work with Microsoft Teams
as you: read your chats and channel conversations, search messages, look up
people and, if enabled, send messages and create meeting links.
It uses **delegated** Microsoft Graph permissions. You sign in once on the
server (OAuth2 authorization code + PKCE), and the server then keeps itself
signed in with the refresh token, getting short-lived access tokens as needed.
Everything it does appears in Teams as done by you.
It runs as a hardened systemd service. No credential is stored in plain text:
| Secret | Where it lives |
|---|---|
| Entra app client secret | TPM-sealed systemd credential |
| MCP access token | TPM-sealed systemd credential |
| Vault key (AES-256) | TPM-sealed systemd credential |
| Microsoft refresh token | `/var/lib/msteams-mcp/vault.json.enc`, AES-256-GCM encrypted with the vault key |
| Access tokens (1 h) | Process memory only |
**Why a vault?** Entra ID *rotates* refresh tokens: every refresh returns a new
one, and each one expires after about 90 days. The server has to save each new
token while it runs, but the sandboxed service can't use the TPM directly. So
the TPM seals a key, and that key encrypts the token file. A copy of the disk
or a backup without this machine's TPM can't read the token.
## Tools
| Tool | Returns / does |
|---|---|
| `whoami()` | The signed-in account and the state of the sign-in |
| `find_people(query)` | Directory lookup by name or email: email, title, department |
| `list_chats(query?, limit?, since?, max_members?)` | Your chats, most recent first: name, last message, UNREAD flag, chat id. With `since`, only chats active since then, and the header says whether the list is complete |
| `get_chat(chat_id)` | Chat details, full member list, meeting join link |
| `read_chat_messages(chat_id, limit?, since?, since_mode?, keep?, include_system?)` | Recent messages as a transcript, oldest first. `since` keeps messages written after it, plus older ones edited after it, marked `(edited <time>)`. If more match than `limit`, `keep="newest"` (default) or `"oldest"` picks the end to keep, and the footer says how many were left out |
| `get_chat_message(chat_id, message_id)` | One message in full |
| `search_messages(query)` | Full-text search over chats and channels (Microsoft Search, KQL) |
| `list_teams()` | Teams you belong to |
| `list_channels(team_id)` | Channels in a team |
| `list_team_members(team_id)` | Team members and roles |
| `read_channel_messages(team_id, channel_id, limit?, include_replies?)` | Recent channel posts with their latest replies |
| `get_channel_thread(team_id, channel_id, message_id)` | A channel post and all replies |
| `send_chat_message(chat_id, content, format?, importance?)` ✏️ | Post in an existing chat |
| `send_direct_message(user, content, format?)` ✏️ | 1:1 message to an email or user_id; creates the chat if needed |
| `send_channel_message(team_id, channel_id, content, format?, subject?)` ✏️ | New channel post |
| `reply_to_channel_message(team_id, channel_id, message_id, content, format?)` ✏️ | Reply in a channel thread |
| `create_online_meeting(subject, start?, end?)` ✏️ | Teams meeting link (no calendar invite) |
**Output.** Read tools return compact text to keep the agent's token use low:
- a chat reads as a transcript, with one date line per day and `HH:MM Sender: text` per message;
- consecutive messages from the same person are grouped;
- times are in UTC;
- ids appear only where a follow-up call needs them: chat ids, post ids, and `[id N]` on messages cut at
`MAX_LIST_TEXT_CHARS`;
- links to open items in Teams and attachment URLs appear only in the single-item tools (`get_chat`,
`get_chat_message`, `get_channel_thread`).
Every read tool also takes `output="json"` for structured data instead. For example, `read_chat_messages` returns:
```
3 messages, oldest first (times UTC)
2026-11-13
10:01 Alice Johnson: Can you check the Q4 numbers? [file: Q4 Forecast.xlsx]
The vendor call moved to Thursday 👍2
10:20 Bob Smith: ↪ Alice Johnson: "Can you check the Q4 numbers?"
On it (edited)
```
✏️ = write tools, registered only when `ENABLE_WRITE_TOOLS=true` (the default).
Set it to `false` for a read-only server. The send tools take `format="text"`
(sent as typed, line breaks kept) or `format="html"` (Teams HTML). To avoid
messaging the wrong person, `send_direct_message` takes an email address (or
user id), not a name.
## Requirements
- **Server:** Linux with systemd 250 or newer and a TPM 2.0 chip (for example
Ubuntu 24.04 or Debian 12), plus Python 3.10+ with `venv` support.
- **Entra ID app registration** (App ID + tenant ID):
- Delegated permissions with admin consent: `openid`, `offline_access`,
`User.Read.All`, `Chat.ReadWrite`, `ChannelMessage.Read.All`,
`ChannelMessage.ReadWrite`, `Group.ReadWrite.All`, `TeamMember.Read.All`,
`OnlineMeetings.ReadWrite`, `TeamworkTag.Read`, `TeamsActivity.Send`.
The server requests `https://graph.microsoft.com/.default`, so it gets
exactly what has been consented.
- **Authentication → Add a platform → Web**, with the redirect URI
`http://localhost`. You can use another localhost URI such as
`http://localhost:8400/callback`; set `MS_REDIRECT_URI` to the exact same
value. Nothing needs to listen on it: you copy the code from the browser's
address bar.
- **Certificates & secrets → New client secret.** Copy its *Value* (not the
Secret ID) straight into `seal-credential.sh client_secret`. Note the expiry
date: when the secret expires the server stops working until you seal a new
one (see below).
## Installation
Run these on the server from a clone of this repository.
```bash
# 1. Install code, venv, service user, config file, vault key and systemd unit
sudo ./deploy/install.sh
# 2. Set your tenant and app id
sudo nano /etc/msteams-mcp/msteams-mcp.env
# 3. Seal the secrets (input is read without echo and never written to disk;
# vault_key was already generated by install.sh)
sudo /opt/msteams-mcp/bin/seal-credential.sh client_secret # paste the app's secret Value
sudo /opt/msteams-mcp/bin/seal-credential.sh mcp_token --generate
# 4. Sign in to Microsoft (see below)
sudo msteams-mcp-authorize
# 5. Start the service and enable it at boot
sudo systemctl enable --now msteams-mcp
# 6. Check it
systemctl status msteams-mcp
journalctl -u msteams-mcp -n 30
curl -s localhost:8766/health # {"status":"ok","auth":"ok"}
```
Show the generated MCP token once, to put in your MCP client config:
```bash
sudo systemd-creds decrypt --name=mcp_token /etc/credstore.encrypted/msteams-mcp.mcp_token.cred -; echo
```
### Signing in
`sudo msteams-mcp-authorize`:
1. prints a `login.microsoftonline.com` URL. Open it in a browser on any
machine and sign in with the account the server should act as;
2. the browser is redirected to `http://localhost/?code=…&state=…` and shows
"can't connect", which is expected;
3. you copy that full URL from the address bar and paste it at the prompt
(input is hidden). The code is single-use, expires in about 10 minutes, and
can only be redeemed with both the client secret and the PKCE verifier held
by the script;
4. the script decrypts the client secret into memory, exchanges the code for
tokens, checks `/me`, and writes the refresh token to the encrypted vault,
owned by the service user.
The running service picks up the new vault on its next request, so you don't
need to restart it.
### When you have to sign in again
The server keeps its sign-in alive by itself. Every refresh rotates the stored
refresh token, and a background refresh every `KEEPALIVE_HOURS` (12 by
default) keeps it fresh even when nobody is using the server. You only need to
run `sudo msteams-mcp-authorize` again when Entra ID rejects the token, for
example:
- your password was changed or reset, or your sessions were revoked;
- an admin revoked consent or disabled the app;
- a Conditional Access sign-in frequency policy, or an MFA requirement, demands
a fresh interactive sign-in;
- the server was off for longer than the refresh token's lifetime (about 90 days).
When that happens, every tool returns *"The saved Microsoft sign-in is no
longer valid (AADSTS…). Run on the server: sudo msteams-mcp-authorize"*,
`/health` reports `"auth":"reauth_required"`, and the journal logs the Entra
error code.
### When the client secret expires
This is a different failure, and you don't need to sign in again: refresh
tokens belong to the App ID, not to a particular secret. Tools return *"Entra
ID rejected the app's client secret (invalid_client: AADSTS7000222…)"*. Create
a new secret in the app registration, then:
```bash
sudo /opt/msteams-mcp/bin/seal-credential.sh client_secret
sudo systemctl restart msteams-mcp
```
Do this before the old secret expires: Entra allows several secrets at once, so
you can switch with no downtime and then delete the old one.
## Connecting a client
The service listens on `127.0.0.1:8766` only (change `PORT` in the unit if needed). The MCP
endpoint is `/mcp`, and every request except `/health` must send
`Authorization: Bearer <token>`. To reach it from another machine, put an HTTPS
front end in front of the port: a reverse proxy (nginx, Caddy), a Tailscale
service, or an SSH tunnel.
```json
{
"mcpServers": {
"msteams_mcp": {
"command": "npx",
"args": ["mcp-remote", "https://your-host.example.com/mcp",
"--header", "Authorization:${AUTH}"],
"env": { "AUTH": "Bearer <your-token>" }
}
}
}
```
Then ask Claude "what are my latest Teams chats?" to confirm it works end to end.
## Agent skill
[`skills/microsoft-teams/`](skills/microsoft-teams/SKILL.md) is an
[Agent Skill](https://agentskills.io) that teaches an agent to use these tools
well: how to find the right chat, read efficiently, and confirm before
sending anything.
- **Claude Code:** `cp -r skills/microsoft-teams ~/.claude/skills/`, then start a new session.
- **claude.ai / Claude Desktop:** `cd skills && zip -r microsoft-teams.zip microsoft-teams`,
then upload it under Settings → Capabilities → Skills.
## Layout on the server
| Path | What |
|---|---|
| `/opt/msteams-mcp/app` | Application code (read-only to the service) |
| `/opt/msteams-mcp/venv` | Python virtual environment |
| `/opt/msteams-mcp/bin` | `authorize.sh`, `seal-credential.sh` |
| `/usr/local/sbin/msteams-mcp-authorize` | Symlink to the sign-in script |
| `/etc/msteams-mcp/msteams-mcp.env` | Non-secret settings |
| `/etc/credstore.encrypted/msteams-mcp.*.cred` | TPM-sealed `client_secret`, `mcp_token` and `vault_key` |
| `/var/lib/msteams-mcp/vault.json.enc` | Encrypted refresh token (0600, user `msteams-mcp`) |
| `/etc/systemd/system/msteams-mcp.service` | The unit |
The service runs as the static system user `msteams-mcp` rather than with
`DynamicUser`. This gives the vault, which the sign-in script writes as root,
a stable owner.
## Configuration
Settings in `/etc/msteams-mcp/msteams-mcp.env` (see [`deploy/msteams-mcp.env.example`](deploy/msteams-mcp.env.example)):
| Variable | Default | Meaning |
|---|---|---|
| `MS_TENANT_ID` | required | Tenant GUID or domain |
| `MS_CLIENT_ID` | required | Application (client) ID |
| `MS_REDIRECT_URI` | `http://localhost` | Must exactly match a redirect URI registered under the *Web* platform |
| `ENABLE_WRITE_TOOLS` | `true` | `false` removes the send/reply/meeting tools |
| `KEEPALIVE_HOURS` | `12` | Background token refresh interval; `0` disables it |
| `MAX_LIST_TEXT_CHARS` | `2000` | Per-message text cut-off in list results |
Restart the service after changing settings.
## Day-to-day
```bash
sudo systemctl restart msteams-mcp # after changing settings or credentials
journalctl -u msteams-mcp -f # follow logs
systemd-analyze security msteams-mcp # hardening score (lower is better)
sudo msteams-mcp-authorize # sign in again / switch account
# Update code: pull the new version, then
sudo ./deploy/install.sh # keeps config, credentials and sign-in
# Replace the client secret (before it expires; no new sign-in needed)
sudo /opt/msteams-mcp/bin/seal-credential.sh client_secret
sudo systemctl restart msteams-mcp
# Rotate the MCP token
sudo /opt/msteams-mcp/bin/seal-credential.sh mcp_token --generate
sudo systemctl restart msteams-mcp # then update your MCP client
# Rotate the vault key (makes the stored sign-in unreadable: sign in again)
sudo /opt/msteams-mcp/bin/seal-credential.sh vault_key --generate --force
sudo systemctl restart msteams-mcp && sudo msteams-mcp-authorize
```
## Notes
- **After a BIOS/firmware update or a Secure Boot change,** the TPM may refuse
to decrypt the credentials, and the service fails to start with a credential
error. Re-seal `client_secret` and `mcp_token`, regenerate `vault_key` with
`--force`, and sign in again.
- **What this protects against:** copies of the disk, backups, sync tools or a
git push picking up files, and other users or services on the server. It
does not stop someone with root on the running machine (root can decrypt
the credentials), so keep SSH key-only and root access tight. The refresh
token is as powerful as your Teams account within the consented permissions.
The client secret alone can't act as you: it only works together with a
refresh token or a fresh sign-in.
- **A certificate instead of a secret** would be stronger (the private key never
leaves the server, and it can last longer). It isn't implemented here.
- **Conditional Access:** if your tenant restricts sign-ins to compliant or
managed devices, or to known locations, refreshes from the server may be
blocked (`AADSTS53003`, `AADSTS50076`...). The journal shows the code.
- **`search_messages`** uses the Microsoft Search API. Results depend on the
search index and can lag a few minutes behind new messages.
- **`create_online_meeting`** creates a join link only. Sending a calendar
invitation would need `Calendars.ReadWrite`, which the app doesn't have.
- If the service fails with a memory-protection error, comment out
`MemoryDenyWriteExecute=yes` in the unit, then run `daemon-reload` and restart.
## Local development
Without systemd, secrets fall back to the `MS_CLIENT_SECRET` / `MCP_TOKEN` /
`VAULT_KEY` environment variables (or to files named by `*_FILE`, for example
`MS_CLIENT_SECRET_FILE`), and the vault is `./vault.json.enc` (override with
`VAULT_PATH`).
```bash
python3 -m venv .venv && . .venv/bin/activate
pip install -r requirements.txt
export MS_TENANT_ID=... MS_CLIENT_ID=... MCP_TOKEN=dev-token
read -rs MS_CLIENT_SECRET && export MS_CLIENT_SECRET # paste, no echo, not in history
export VAULT_KEY=$(python -c 'import vault; print(vault.new_key_text())')
python authorize.py # interactive sign-in -> ./vault.json.enc
python server.py # serves http://127.0.0.1:8766/mcp
```
Offline tests (Graph and Entra ID are mocked, no tenant needed):
```bash
python tests/test_day_review.py -v # -v prints sample output
```
## License
MIT, see [LICENSE](LICENSE).
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues