Skip to content
dateoPublic

About

phei is an MCP server that lets AI agents keep their humans informed and ask them things on a web inbox, the terminal, Teams, Outlook, Slack, Rocket.Chat, Matrix, mail, Signal, WhatsApp or any channel a plugin adds.

Topics

Resources

Contributing

Security policy

Stars

4 stars

Watchers

0 watching

Forks

Repository files navigation

phei

phei is an MCP server that lets AI agents keep their humans informed and ask them things on a web inbox, the terminal, Teams, Outlook, Slack, Rocket.Chat, Matrix, mail, Signal, WhatsApp or any channel a plugin adds.

It speaks the Model Context Protocol and is written in Go. One phei serves many agent sessions for many users at once. The documentation covers each channel and feature in detail.

The name

Phei is short for Pheidippides (Φειδιππίδης, also spelled Philippides), the runner of Athens.

In 490 BC, when the Persians landed at Marathon, Athens sent Pheidippides to Sparta to ask for help. Herodotus says he ran about 240 km in two days, then brought back an answer that was not the one Athens hoped for: the Spartans would come, but not before the full moon. Later legend has him run the 40 km from the battlefield back to Athens to report the outcome. He gasped "Nenikēkamen", "we have won", and died.

Those are this server's two jobs:

Pheidippides phei
ran to Sparta to ask, and came back with an answer that took its time ask_user, await_answer
ran to Athens to report how it went notify_start, notify_progress, notify_end

Unlike the original, phei is fine with a 24-hour wait for an answer. The plugin handshake cookie is nenikekamen.

Tools

Tool Does
notify_start Announces a piece of work and returns a run_id.
notify_progress Reports progress. Updates are merged (at most one per progress_interval) and edited in place where the channel allows.
notify_end Ends the run with success, failure or cancelled and a summary.
ask_user Asks a confirm, choice, text or form question, optionally with an A2UI surface, and waits up to wait_seconds (default 20). If nobody answers by then, the result is pending with a question_id.
await_answer Waits for a pending question again. Any session of the same user can call it, including an agent that reconnected.
cancel_question Withdraws a question.

People answer in minutes or hours, so ask_user never blocks a tool call for long. The agent gets pending, carries on with work that does not depend on the answer, and calls await_answer later. Every question has a timeout (timeout_seconds, by default defaults.ask_timeout). When it runs out, phei either answers with the agent's default or reports expired.

Many sessions, many users

flowchart LR
    subgraph agents["agents, each with its user's token (alice's, bob's …)"]
        cc[claude-code]
        cursor
        codex
        ci[a CI agent]
    end
    subgraph channels["channels"]
        inbox["inbox (web, TUI)"]
        ms["teams / outlook"]
        chat["slack, rocket.chat, matrix"]
        mail
        more["signal, whatsapp, plugins …"]
    end
    agents -- "MCP + bearer token" --> phei
    phei --> inbox & ms & chat & mail & more
Loading
  • Over streamable HTTP (phei serve), every agent connects to /mcp with a bearer token. The token names the user and every MCP session belongs to that user. The MCP SDK refuses to let another token take a session over.

  • The user is the security boundary. A session sees only its user's runs and questions. Only that user can answer, and only from an address configured for them on the channel (an answer from an unknown Slack user is refused). A reconnected agent of the same user can still await an earlier question.

  • The session is the context. Every message says which agent and session it comes from, so a user with three agents running knows who is asking.

  • The first answer wins. A question can go out on several channels, and escalate to more over time (after:). The first valid answer settles it, and every other channel's message is closed or updated ("answered by alice via teams").

  • When a session ends, its active runs become abandoned. Its open questions stay open until they time out.

  • Restarts lose nothing when state_file is set. Open questions, runs, answers and the messages already sent on each channel are kept in a bbolt file. After a restart:

    • questions get their timeouts and pending escalations back, and whatever came due meanwhile happens at once;
    • a reconnecting agent continues its runs and awaits its questions by id;
    • active runs whose agent does not report within run_grace become abandoned.

    Answered questions and ended runs are dropped after retention.

  • Over stdio (phei serve --stdio --user alice) there is one session. phei also serves the inbox on listen if that port is free. If another phei holds the port, answers must come through a channel. The same goes for the state file: only one phei can hold it, and a second stdio phei keeps its state in memory. For several agents, run one phei serve.

Logging in and tokens

Agents, the TUI and scripts authenticate with a bearer token. Every token belongs to one user.

  • Users make their own tokens on the web inbox's Tokens page. Each token has a name, an expiry (30 or 90 days, a year, or never) and a "last used" time, and can be revoked. A new token is shown once, together with ready-to-paste commands for Claude Code and the TUI. phei keeps only the token's SHA-256, in the state file.
  • Tokens in the config (token_sha256, added by phei token) suit headless setups. phei reads them at start. phei token check -c phei.yaml tells which user a token belongs to.

The web inbox takes a token too, or, with oidc configured, a login through your identity provider (Entra ID, Keycloak, Authentik, …). The ID token's claim (default email) has to match a configured user's oidc value, or their id. Only configured users can log in.

oidc:
  issuer: https://login.microsoftonline.com/<tenant id>/v2.0
  client_id: <client id>
  client_secret_env: PHEI_OIDC_SECRET
  name: Microsoft            # the login button says "Log in with Microsoft"
users:
  - id: alice
    oidc: alice@example.com

Register <public_url>/auth/callback as the redirect URI. phei uses the authorization code flow with PKCE, and checks state and nonce.

Channels

Each channel is a driver. The inbox and log drivers are built in. Everything else is a plugin: a phei-driver-<name> binary in plugin_dir, run as a hashicorp/go-plugin gRPC subprocess. phei starts only the plugins that have a section under drivers: in the config, so a plugin directory (or the Docker image) can hold more than you use. An empty section, e.g. signal: {}, runs a plugin on its defaults.

  • Hot reload. The plugin directory is watched. When a binary is dropped in or replaced, it is started, configured and swapped in, and the old generation is stopped. A plugin that dies is restarted on the next delivery.
  • phei owns all state (sessions, runs, questions, message refs), so a reload loses nothing.
  • phei owns all inbound HTTP. Channel callbacks arrive at /inbound/<driver>/… and are handed to the driver's HandleInbound. Plugins never open ports. Channels with their own connection (Slack socket mode, a Signal daemon, IMAP IDLE) stream answers back over Answers.
  • Capabilities (buttons, freeText, forms, editInPlace, inbound, secure) tell phei what a channel can do. A sensitive question sends only an answer link to an insecure channel.
  • Every question carries a signed answer link to the web inbox. It is the fallback for any channel that cannot take the answer itself.
  • One plugin can serve several channels, each with its own capabilities, for example one bot behind both Teams and Outlook. Routes name the channels.
  • A click learns how it went. A plugin can defer its response to an inbound request until phei has applied the answer. The clicked card then says "thanks" or "already answered by bob via inbox".

Available:

Channel Plugin How
teams microsoft Adaptive Cards in the user's chat with the phei bot, answered with Universal Actions; progress updates the card in place
outlook microsoft Actionable Messages through Microsoft Graph: the same card in Outlook, plus an HTML body with the answer link for other clients
matrix matrix DMs from a bot account, edited in place, optionally end-to-end encrypted; people answer by reacting (👍/👎, an option's number) or replying in the question's thread
rocketchat rocketchat DMs from a bot user, edited in place; people answer by replying (yes/no, an option's number, text, field: value lines), which phei reads against the question
slack slack DMs from the phei app over Socket Mode: buttons, a select menu, or a form in a modal; replies in the thread work too; edited in place
mail mail SMTP out; people answer by replying (or with one-click mailto: buttons), read over IMAP IDLE and matched to the question by a tag signed for the recipient
signal signal Messages from phei's own number through the signal-cli daemon, edited in place within Signal's limits; people answer by replying (quoting the question when several are open) or with 👍 / 👎
webpush built in Browser push notifications (Web Push with VAPID; keys made on the first start); people turn them on per browser under Settings in the web inbox, and answer yes/no and two-option questions on the notification itself
whatsapp whatsapp Messages from phei's business number through the WhatsApp Cloud API: reply buttons or a list for choices, replies for the rest; outside WhatsApp's 24-hour window an approved template goes first and the question follows when the person writes back

Setup: docs/matrix.md, docs/microsoft.md, docs/rocketchat.md, docs/slack.md, docs/mail.md, docs/signal.md, docs/webpush.md, docs/whatsapp.md.

Channels without buttons hand phei what the person typed, and phei reads it against the question (driver.ParseTextAnswer), so every such driver answers the same way.

SMS is left out for now.

A2UI

A form question can carry an A2UI surface: an array of A2UI v0.9 messages, the version the terminal renderer speaks. Its answer is {"action": <the event of the button pressed>, "values": {<field id>: …}}. Each driver renders what it can (Adaptive Cards for Teams and Outlook, Block Kit for Slack, the TUI natively) and degrades the rest to the plain question plus the answer link.

The terminal

phei tui is the inbox in a terminal. It lists open questions and running work, updates live, and answers questions in place:

PHEI_TOKEN=<token> phei tui --url http://127.0.0.1:7777

Every question is drawn as an A2UI surface by a2tea (A2UI → Bubble Tea). phei builds that surface itself for the plain kinds: Yes/No buttons, option buttons (or a picker for many options), a text field, or fields from the form's JSON Schema. An agent's own v0.9 surface is shown as sent. A surface the renderer cannot draw, such as A2UI v1.0, falls back to the plain form with a note. a2tea is used in internal/tui/render.go only, so it can be swapped out.

Writing a driver

package main

import (
	"context"

	"github.com/dateo/phei/pkg/driver"
	"github.com/dateo/phei/pkg/sdk"
)

type myDriver struct{ driver.Base }

func (myDriver) Describe(context.Context) (driver.Info, error) {
	return driver.Info{Name: "my", Capabilities: driver.Capabilities{Buttons: true}}, nil
}

func (myDriver) Deliver(ctx context.Context, d driver.Delivery) (string, error) {
	// post d to the channel, return the message's id
	return "", nil
}

func main() { sdk.Serve(myDriver{}) }

Build it as phei-driver-my into plugin_dir. Its section under drivers.my in the config reaches Configure as JSON; without one, phei does not start it. examples/phei-driver-echo is a complete, minimal example. The gRPC contract is proto/phei/driver/v1/driver.proto, so drivers can be written in other languages too.

A driver that takes callbacks must verify them (Teams' bearer JWT, Slack's signing secret, …). phei trusts the identity a driver reports, and then only if it matches a configured address.

A driver can also pass on messages from people to their agents (see Talking back to agents): an Answer with Command (stop, prompt with Text, or status) and the RunID it is for, instead of a QuestionID. phei maps the sender like for an answer, accepts it only from the run's owner and only while the run is active, and reports how it went through CompleteInbound, with an Error meant for the person to read.

Signed plugins

A plugin runs with phei's rights and sees every question it carries, so phei can require plugins to be signed with minisign:

minisign -G -p phei-plugins.pub -s phei-plugins.key      # once
minisign -S -s phei-plugins.key -m plugins/phei-driver-slack

The second command writes phei-driver-slack.minisig next to the binary. List the keys phei trusts:

plugin_keys:
  - phei-plugins.pub          # a .pub file, relative to the config
  - RWQf6LRCGA9i53mlYecO4…    # or the key itself

With plugin_keys set, phei starts only plugins whose signature checks out against one of the keys. A binary without a signature, signed by another key, or changed after signing is not started. On a hot reload the running generation then stays. The log names the key and the signature's trusted comment (signed="5EAADF5E5A499D3D (timestamp:… file:phei-driver-slack)"). Copy the binary first and the .minisig after it: the signature arriving is enough to start the plugin. To check a signature by hand, use minisign -V -p phei-plugins.pub -m plugins/phei-driver-slack.

phei checks the bytes it reads and starts exactly those, from a copy in a private directory, so a binary swapped in after the check is not run. That directory is a fresh temporary one, or plugin_exec_dir where /tmp is mounted noexec.

Without plugin_keys, plugins start unsigned and phei warns about it once at startup.

Quick start

go install github.com/dateo/phei@latest   # or, in a checkout: go build .
phei token        # writes phei.yaml with you as its user, and your token to .env
phei serve
phei tui          # in another terminal; reads the token from .env

phei token adds a token to an existing config the same way (-u names the user; a new name adds a user). It also writes PHEI_TOKEN and PHEI_URL to the .env next to the config (--no-env skips that). When the directory is in a git repository, it adds .env, the config (it holds the secret) and the state file to the .gitignore there. phei.example.yaml shows every option.

phei listens on every interface (listen: ":7777"), so agents in containers and on other machines reach it; public_url defaults to this host's name. listen: 127.0.0.1:7777 (or phei serve --listen 127.0.0.1:7777) keeps it to this machine. Over plain HTTP, tokens cross the network unencrypted, and phei warns about it: beyond a trusted network, put a TLS proxy in front and set public_url to it.

Open http://127.0.0.1:7777 and log in with the token, or run PHEI_TOKEN=<token> ./phei tui. Then point an agent at it, for example Claude Code:

claude mcp add --transport http phei http://127.0.0.1:7777/mcp \
  --header "Authorization: Bearer <token>"

or, for a single local agent, use stdio:

claude mcp add phei -- /path/to/phei serve --stdio -c /path/to/phei.yaml

For Claude Code there is also a plugin: phei's MCP tools plus hooks that report every turn as a run, hand Claude your messages before each tool call, stop it when you say so, and, while you are away, ask you about permission prompts and let you continue a finished turn from your phone:

claude plugin marketplace add https://github.com/dateo/phei.git
claude plugin install phei@phei

See docs/claude-code.md.

Docker

The image holds phei and every channel plugin, Matrix with encryption included. Mount a config at /etc/phei/phei.yaml and a volume for state at /var/lib/phei:

docker run -d --name phei -p 7777:7777 \
  -v ./phei.yaml:/etc/phei/phei.yaml:ro -v phei-data:/var/lib/phei \
  --env-file secrets.env ghcr.io/dateo/phei:latest

docs/docker.md has the config paths, a Compose file and how to build the image.

How agents ask you

Many agents have their own way to ask you, such as a prompt in their window. Your question mode decides how that and phei work together. It is yours, set once, and every agent session you start follows it, in any repository and with any MCP client. phei delivers it as part of the MCP server instructions, which clients put in the agent's system prompt.

Mode Agents… For
mirror (default) ask in their own window and through phei (ask_user with wait_seconds: 0), take whichever answer comes first, and withdraw the other (cancel_question) working at the machine, or away from it
phei ask only through phei unattended or remote work
local ask only in their own window; phei gets their progress reports working at the machine, phei for overview

Set it on the web inbox's Settings page, or with phei settings question-mode mirror|phei|local (it uses your token, like phei tui). phei settings shows the current value. A change applies to agent sessions started after it; running sessions keep the instructions they got.

Talking back to agents

From the web inbox you can reach a running agent: on its run, or on a connected agent session, press Status?, Stop or Prompt…. On Matrix you do it on the run's message: reply in its thread to prompt, react ⏹ to stop or 🔄 for the status. With only one run active, writing straight into the DM works too (docs/matrix.md).

Message The agent…
Stop stops as soon as it is safe, ends its run as cancelled, says where it left off, and waits
Prompt takes your text as a new instruction, as if you had typed it to it
Status? reports where it is with notify_progress on its run, which you see on the run card and in your channels

MCP has no way to push into an agent's conversation. Your message therefore reaches the agent with its next phei tool call: in the from_human field of any phei tool result, or through check_messages, which the instructions tell agents to call between steps of long work. A message also ends a pending await_answer early, so a stop is not held up by an open question. The inbox shows whether a message was delivered or is still waiting for the agent to check in. A message for a run also reaches the agent if it comes back in a new session (after a phei restart, say) and reports on that run. The API is POST /api/messages with kind (stop, prompt, status), text, and a run_id or a session_id.

With the Claude Code plugin, Claude doesn't have to call phei to hear from you: hooks hand it your messages before every tool call, turn tool calls away after a stop, and answer status requests for it.

Agent teams

Your agents can work together through phei, across terminals, machines, containers and agent makes. The first agent of a team leads it; agents that join later are its subordinates.

  • Peers: each sees what the others work on and the pressure they are under (usage limits hit, context compactions, host load), and can ask them for their status.
  • Tasks: agents hand tasks to each other or to idle workers (phei team worker, e.g. in containers). A task whose agent hits its usage limit goes back to the team.
  • Leader: a subordinate's ordinary questions go to the leader first, which answers or forwards them to you; sensitive questions and permission prompts always come to you. You can choose the leader on the web inbox's Teams page or with phei team lead; agents can't move it away from your choice.
  • Same repository: a Claude Code session that starts where another agent of yours works makes phei ask you whether it should join that agent's team.

See docs/agent-teams.md; phei team shows your teams.

Usage

Agents report what they used: tokens (input, output, cache), cost, model, time, and the OS user and host they run as. phei sums it up per user, by machine (user@host), model, agent and day. See the web inbox's Usage page, phei usage (--days 7), or GET /api/usage?days=30.

Reports are totals of one agent session so far. A later report of the same session and model replaces the earlier one, so reporting often never counts anything twice. There are two ways in:

  • report_usage, an MCP tool, for agents whose client tells them their usage. Its description tells agents to report only numbers they are given. An LLM agent usually does not know its own token counts, so for Claude Code use the hook below.

  • phei usage hook, for Claude Code. As a Stop (after every turn) and SessionEnd hook, it reads the session transcript the hook points to, sums the token counts Claude Code recorded there per model, and reports them with this machine's OS user, host name and project directory. It never fails the hook; problems go to stderr. In ~/.claude/settings.json:

    {
      "hooks": {
        "Stop":       [{ "hooks": [{ "type": "command", "command": "phei usage hook --env-file ~/phei/.env" }] }],
        "SessionEnd": [{ "hooks": [{ "type": "command", "command": "phei usage hook --env-file ~/phei/.env" }] }]
      }
    }

    --env-file points at the .env that phei token wrote. Setting PHEI_TOKEN and PHEI_URL in Claude Code's env settings works too. Claude Code's transcript has tokens but no prices, so the hook reports no cost.

Scripts can report with phei usage report or POST /api/usage. Each user sees only their own usage. Records are kept for 400 days.

Restarts and outages

phei can restart, or be unreachable for a while, without its clients noticing much:

  • Agents keep their MCP session. The MCP Go SDK forgets sessions on restart, and an agent would then get 404 and have to start over, which not every client does well. With a state_file, phei records how each session was initialized. When a request comes in for a session it no longer knows, phei initializes that session again under the same id and then serves the request. Runs and questions survive restarts anyway, so the agent carries on where it was. A session the client ended (DELETE) stays ended. A session can be revived only by its own user's token, and records are forgotten after 30 days.
  • phei tui starts even while phei is down, shows reconnecting, and reconnects on its own, retrying after one second at first and then less often, up to every 30 seconds. Once connected again, it catches up on what it missed.
  • The web inbox shows a banner while phei is unreachable, retries on its own, and refreshes once its live connection is back. It asks you to log in only when phei says the login no longer counts. That happens after a restart only if no fixed secret is configured.
  • The channel plugins reconnect to Slack, Rocket.Chat, Matrix and the Bot Framework by themselves, and phei restarts a plugin that died.

Stdio sessions end with the process that serves them. The MCP client starts a new one.

Development

go test -race ./...
eval "$(hack/matrix-synapse.sh)" && go test -race -tags goolm ./drivers/matrix/   # Matrix against a real Synapse
go run ./hack/protogen   # regenerate pkg/driverpb after changing the proto (no protoc needed)
docker build -t phei .   # the image; see docs/docker.md

On GitHub, .github/workflows/ci.yml runs gofmt, go vet and the tests with the race detector (Matrix included, against a throwaway Synapse) on every push and pull request. When they pass, it builds the image for amd64 and arm64 and pushes it to ghcr.io/dateo/phei: for main as tag main, and for version tags (v1.2.3 becomes 1.2.3, 1.2 and latest). Pull requests build the image without pushing.

Status

Early. Working:

  • the broker (multi-session, multi-user, routing, escalation, timeouts, first answer wins)
  • the MCP tools over HTTP and stdio
  • the web inbox with live updates and signed answer links
  • the terminal inbox (phei tui) with A2UI surfaces
  • persistence in bbolt, including timeouts, escalations and runs across restarts
  • OIDC login for the web inbox, and tokens users make and revoke themselves
  • the plugin host with hot reload and minisign signature checks, and the echo example
  • the Claude Code plugin (MCP plus hooks), tested with Claude Code 2.1.332
  • agent teams: peers, tasks, workers (with a container example) and a leader, tested with Claude Code 2.1.332 as a worker
  • Teams and Outlook (phei-driver-microsoft), tested against a simulated Microsoft so far
  • Matrix (phei-driver-matrix), with optional end-to-end encryption, tested against a real Synapse
  • Rocket.Chat (phei-driver-rocketchat), tested against a simulated Rocket.Chat so far
  • Slack (phei-driver-slack), tested against a simulated Slack so far
  • mail (phei-driver-mail), tested against local SMTP and IMAP servers so far
  • Signal (phei-driver-signal), tested against a simulated signal-cli so far
  • WhatsApp (phei-driver-whatsapp), tested against a simulated Cloud API so far
  • browser push notifications (webpush, built in), payload encryption checked against RFC 8291's example, tested against a simulated push service so far

Next:

  • running the channel drivers against the real services

Contributing and reporting bugs

Report a bug with the bug report template; CONTRIBUTING.md says what to include and how to propose a change. Security problems go to a private advisory, not an issue: see SECURITY.md.

License

Apache License 2.0

About

phei is an MCP server that lets AI agents keep their humans informed and ask them things on a web inbox, the terminal, Teams, Outlook, Slack, Rocket.Chat, Matrix, mail, Signal, WhatsApp or any channel a plugin adds.

Topics

Resources

Contributing

Security policy

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages