Expose Dayflow as an MCP Server
For eleven lessons Dayflow was the agent. Now it becomes the tools, and someone else's model is holding them.
What you will be able to do
- Serve an existing tool registry over MCP without rewriting a single tool
- Say which controls must live on the server side, and why the client's permission prompt is not one of them
- Test an MCP server three ways: in-process, over real stdio, and with a second agent
- Spot the context that does not travel with your tools, and send it another way
lesson-92. New: dayflow/mcp_server.py (about 80 lines), dayflow mcp, tests/test_mcp_server.py. New dependency: the mcp Python SDK, version 2. You met MCP as a user in the primer; this is the other side of it.Agent or tools: the same code, a different owner
| Dayflow as an agent (81 to 91) | Dayflow as an MCP server (92) | |
|---|---|---|
| Who runs the model | Dayflow | The client: Claude Code, Claude Desktop, another agent |
| Who wrote the system prompt | You | Someone else. You never see it. |
| Who decides when to call a tool | Your loop | Their loop |
| What you still own | Everything | The tool surface, the results, and what a call is allowed to do |
Lesson 82 set the tools up as an API surface with strict schemas and one result envelope, and left a comment in the code: "lesson 92 exposes it over MCP unchanged". That is nearly the whole implementation.
def build(store: Store, *, read_only: bool = False) -> Server:
kinds = ("read",) if read_only else ("read", "write")
run_id = store.create_run(kind="mcp", system="", user_msg="", model="(mcp client)")
gate = permissions.gate_for("queue", store=store, run_id=run_id)
async def list_tools(ctx, params) -> types.ListToolsResult:
return types.ListToolsResult(tools=[
types.Tool(name=t.name, description=t.description, input_schema=t.schema()["input_schema"],
annotations=types.ToolAnnotations(read_only_hint=t.kind == "read", ...))
for t in tools.REGISTRY.values() if t.kind in kinds])
async def call_tool(ctx, params) -> types.CallToolResult:
tool = tools.REGISTRY.get(params.name)
if tool is None or tool.kind not in kinds:
out = json.dumps({"ok": False, "error": {"code": "unknown_tool", ...}})
else:
out = gate.call(params.name, dict(params.arguments or {})) # the same Gate as the loop
env = json.loads(out)
code = (env.get("error") or {}).get("code")
return types.CallToolResult(content=[types.TextContent(type="text", text=out)],
is_error=not env["ok"] and code not in REFUSALS)
return Server("dayflow", version=__version__, instructions=INSTRUCTIONS + today,
on_list_tools=list_tools, on_call_tool=call_tool)Two handlers. list_tools walks the registry. call_tool hands the call togate.call, the same function the raw loop has used since lesson 86. Retries from lesson 91, content rules and taint from lesson 88, the write limit: all of it comes along because it was never in the loop to begin with.
Every time a lesson moved a rule out of the prompt and into code (the write limit in 86, the content rules in 88, retries in 91), it looked like extra work. This lesson is where it pays. A prompt-level rule protects one agent. A rule in
dispatch() or the Gate protects every caller, including ones that did not exist when you wrote it.Four decisions the server has to make for itself
1. Writes are always queued
The agent could ask at a terminal. A server has no terminal, and the model on the other end was prompted by someone else. So the gate is built in queue mode with no option to change it: a write is recorded and returned as pending_approval.
MCP clients have their own "allow this tool?" prompt. It is a good thing and it is not yours. The user may have clicked "always allow"; another client may not ask at all. A control you cannot see does not count as one of your layers.
2. There is no approve tool
It would be easy to add approve_write(id) so the whole flow happens inside the chat. Then the model that proposed the write can approve it, and the approval queue is decoration. Approving stays indayflow approve, typed by a person, outside the protocol. A test asserts no listed tool name contains "approv".
3. A refusal is not a protocol error
MCP results carry an is_error flag. A queued write has ok: false in Dayflow's envelope, but it is not a failure: the call was understood and deliberately not carried out. Marking it as an error invites the client to retry or apologise. So is_error is true only for real failures (an outage, a bad tool name) and false for pending_approval,write_limit and content_rule, whose envelopes say what happened.
4. A session is a run
Each client connection creates a run of kind mcp. Its proposals are grouped under that run indayflow approvals, the two-writes-per-tool limit applies to the session, and a session that read flagged mail is tainted for its whole life.
Test it three ways
In-process, with the real client
async def test_a_write_is_queued_never_run_and_is_not_reported_as_a_protocol_error(store):
before = store.list_tasks()
async with Client(mcp_server.build(store)) as c: # the real MCP client, no subprocess
r = await c.call_tool("create_task", {"title": "Call the bank", "due": None, "idempotency_key": "k1"})
env = json.loads(r.content[0].text)
assert env["ok"] is False and env["error"]["code"] == "pending_approval"
assert r.is_error is False
assert store.list_tasks() == before
assert store.list_approvals()[0]["id"] in env["error"]["message"]Nine tests, under a second, no model and no network. They cover the surface (schemas identical to the registry), the queue, the read-only mode, the write limit per session, and lesson 88's hostile inbox: a session that read it cannot draft to the attacker, over MCP, with no extra code.
Over real stdio
server: dayflow 0.92.0
read_inbox read_only=True
read_calendar read_only=True
read_tasks read_only=True
create_task read_only=False
draft_reply read_only=False
[dayflow mcp] read_tasks -> ok
read_tasks -> {"ok": true, "data": [{"id": "t3", "title": "Send Sept newsletter draft", ...
[dayflow mcp] create_task -> pending_approval
create_task -> is_error = False
{"ok": false, "error": {"code": "pending_approval", "message": "Not executed. Queued for the
user's approval as ap_742291. Do not retry. ...", "retryable": false}}On stdio the protocol messages travel over the process's stdout. One stray
print() and the client receives a line that is not JSON and drops the connection, usually with an error that does not mention your print. The two [dayflow mcp] lines above go to stderr. Check every code path your server can reach for prints, including libraries.With somebody else's agent
The real test is a model you did not prompt. This is a separate Claude Agent SDK agent with a one-line system prompt of its own ("You are a general assistant. Use the dayflow tools when the user asks about their day."), connected to dayflow mcp over stdio:
> What is due this week according to my tasks? Then add a task to call the bank about my card on Wednesday.
TOOL mcp__dayflow__read_tasks {'include_done': False}
TOOL mcp__dayflow__create_task {'title': 'Call the bank about my card', 'due': '2026-09-09',
'idempotency_key': 'call-bank-card-2026-09-09'}
**Due this week (week of 2026-09-07):**
- Send Sept newsletter draft: Tue 2026-09-08
- Review vendor comparison from Priya: Fri 2026-09-11
**Waiting for your approval:**
- Call the bank about my card, due Wed 2026-09-09. I haven't created this task yet. It's queued as
`ap_bcae45`, and you can create it by running `dayflow approve ap_bcae45`.
RESULT turns=3 cost=$0.0072 6.6s
$ dayflow approve ap_f5d938
approved ap_f5d938: {'id': 't5', 'title': 'Call the bank about my card', 'due': '2026-09-09', 'done': False, 'created': True}A model that has never seen Dayflow's prompt read the envelope, did not claim the task existed, and told the user the exact command. It knew the command because of the server's instructions, a short text sent when the client connects. (The approve line is from the first of two runs, which is why the id differs.)
What did not travel
The first run of that same test answered the question and then added this:
The first two fall in the week of Sept 7-11. Today's date in my context is 2026-11-13, so those dates are already past.
Lesson 84 found this bug once: the prompt asked about "today" without saying what day it was. The fix went into Dayflow's own prompt. The MCP client never receives that prompt, so the bug came back one layer out. Anything your agent knew only because you told it in the system prompt is missing for every other caller.
# The client's model was not given our prompt, so it does not know what "today" is here.
# Instructions are the only prompt we get to send.
today = f" Today is {clock.today()}; interpret every date in results relative to that."
return Server("dayflow", version=__version__, instructions=INSTRUCTIONS + today, ...)The second run, shown above, got it right. Two cautions. Whether a client passes server instructions to its model is the client's choice; this one did, and you should not assume all do. And tool descriptions are the one piece of text every client must show the model, so anything a caller cannot work without belongs there or in the result itself. One leftover is visible in the output: the queued-write message still says "list it in the brief", wording written for Dayflow's own agent.
Using it
dayflow mcp # all five tools, writes queued dayflow mcp --read-only # read_inbox, read_calendar, read_tasks only
Any MCP client that can launch a stdio server can use it: give it the command dayflow mcp and the folder to run in. Start with --read-only. The read tools hand a third-party model your inbox, which is a bigger decision than it sounds: lesson 88 was about what an email can do to a model, and now it is a model whose prompt and other tools you have not seen. If that client also has a tool that can send data somewhere, Dayflow's "no send tool" guarantee no longer covers the whole system.
Hand your tools to another agent
Steps 1 to 4 are free. Use a scratch database: export DAYFLOW_DB=/tmp/l92.db
- Run `pytest tests/test_mcp_server.py -v`. Nine pass. Find the test that proves the hostile inbox from lesson 88 is still handled, and note that mcp_server.py contains no security code.
- Read dayflow/mcp_server.py top to bottom. It is about 80 lines. List every control it relies on and the lesson that built it.
- Write a ten-line client: `from mcp import Client, StdioServerParameters`, launch `python -m dayflow.main mcp`, list the tools, call read_tasks, call create_task. Print is_error and the envelope for each.
- Run `dayflow approvals`, then `dayflow approve <id>`, then call read_tasks again from your client. Then try create_task three times in one session and read the third envelope.
- Break the wire on purpose: add `print("hello")` at the top of call_tool, rerun your client, and read the error you get. Would you have guessed the cause? Remove it.
- Register the server with an MCP client you use (Claude Code or Claude Desktop), read-only first. Ask it what is due this week. Does it know what today is? Check whether your client passed the server instructions on.
- Switch to the full server and ask the client to add a task. Does it claim the task was created? If it does, improve the pending_approval message in permissions.py so it works for a caller that has never seen the brief prompt, and update the test that pins it.
- Design question, no code: a teammate wants an approve tool "for convenience". Write the three sentences you would send back.
What this lesson deliberately does not do
- Serve over HTTP. stdio means the server runs on the user's machine as the user. A remote server needs authentication for every client and a database that is not a local file; both belong with deployment.
- Expose resources or prompts. MCP has both. A
morning_briefprompt would be a natural addition; the tools are enough to show the pattern. - Verify real clients by hand. The server was exercised by the MCP SDK's own client and by a Claude Agent SDK agent. Registering it in Claude Code or Claude Desktop is step 6 above, and I have not done it for you.
- Serve real Google in the test runs.
MOCK=0 dayflow mcpuses the lesson 87 adapters. It is wired and untested here. - Mirror it in TypeScript. Python only.
A process that lists tools and runs calls for a client. The client owns the model, the prompt and the loop.
Serves the registry over stdio. --read-only lists the three read tools only.
Same names, descriptions and strict schemas as the API sees. list_tools walks tools.REGISTRY.
call_tool calls gate.call. Retries, content rules, taint and the write limit apply without new code.
Writes return pending_approval. The client-side permission prompt is the clientโs control, not the serverโs.
Approval is typed by a person in the CLI. A proposer that can approve makes the queue meaningless.
True for real failures only. A refusal (pending, limit, content rule) is a normal result the model must read.
Text the server sends at connect. Carries the envelope rules and todayโs date. Not every client is guaranteed to pass it on.
On stdio, any print to stdout corrupts the protocol. Log to stderr.
Whatever your agent knew only from your system prompt is missing for every other caller.