6. Safe writes¶
Reading a catalog cannot hurt anyone. Borrowing a book changes the world: a copy leaves the shelf and someone else cannot have it. Step 3 adds borrowing and returning, and this chapter is about the two ways writes go wrong with agents:
- The model acts without the person agreeing. It misreads "can I borrow this?" as "borrow this".
- A write happens twice. A call times out, the host retries, and the book is borrowed twice.
A server you can build fresh¶
Writes change state, so tests need a fresh library each time. Step 3 builds the server in a function:
def build(library: Library | None = None, *, approver: Approver | None = None) -> OunceServer:
server = OunceServer(
"shelf",
instructions="A library. Search for books, borrow them and return them.",
deps=library or Library(),
approver=approver,
)
deps= is whatever your tools need (a database pool, an API client, here the Library), read in tools as ctx.deps. The module still ends with server = build(), so ouncemcp dev and hosts find it as before.
Asking first¶
async def borrow_preview(book_id: str, ctx: ToolContext) -> str:
book = ctx.deps.books.get(book_id)
title = book.title if book else book_id
return f"Borrow '{title}' ({book_id}) for 3 weeks? It will be due back on the 21st day."
@server.tool(
name="loans.borrow",
effect=Effect.WRITE,
approval="required",
preview=borrow_preview,
idempotency=True,
)
async def borrow(
ctx: ToolContext,
book_id: str = Field(description="Book id from books.search"),
) -> LoanOut:
"""Borrow a book for three weeks. The server asks the user to confirm, so call
it directly. Side effect: creates a loan. Use loans.mine to see current loans."""
book = ctx.deps.books.get(book_id)
if book is None:
raise NotFound(f"No book with id '{book_id}'.", hint="Use books.search to find ids.")
if ctx.deps.available(book_id) < 1:
raise PermissionDenied(
f"All copies of '{book.title}' are on loan.",
hint="Tell the user; suggest another book by the same author.",
)
return loan_out(ctx, await ctx.deps.borrow(book_id, MEMBER, BRANCH))
Look at the decorator:
effect=Effect.WRITEsays the tool changes state.approval="required"asks the person before the handler runs. If they decline, the handler never runs and the model getsapproval_declined(categorypermission).preview=borrow_previewwrites the question. It takes the same arguments as the tool, must not change anything, and should say exactly what will happen: "Borrow 'The Forest Forest' (b-002) for 3 weeks?" is a question a person can answer; "Allow loans.borrow?" is not.
How the question reaches the person depends on the client. Current clients get an MCP input_required result with a signed, single-use receipt; older clients that support elicitation are asked directly. A client that can do neither is refused, unless the server has an approver hook:
An approver receives an ApprovalRequest (tool, arguments, caller, preview text) and returns True or False. Use it to route approvals to a ticket queue or a chat bot, and in tests.
Warning
The model cannot approve its own write. There is no argument for it (approval and approved are reserved parameter names), and only the client's answer to the server's own question counts.
The description says "The server asks the user to confirm, so call it directly." Without that sentence, models tend to ask the user in chat first and then call the tool, so the person is asked twice.
approval can also be a function, for writes that need a yes only sometimes:
@server.tool(name="fines.waive", effect=Effect.WRITE, approval=lambda r: r.arguments["amount"] > 20)
Happening once¶
idempotency=True keys each write by the caller, the tenant and the arguments. A second identical call does not run the handler: it replays the first result. The test for this chapter borrows b-002 twice and checks there is one loan.
@server.tool(name="loans.return", effect=Effect.WRITE, idempotency=True)
async def give_back(
ctx: ToolContext,
loan_id: str = Field(description="Loan id from loans.mine, for example L-1"),
) -> LoanOut:
"""Return a borrowed book. Side effect: marks the loan returned and frees a copy.
Use loans.mine to find loan ids."""
loan = ctx.deps.loans.get(loan_id)
if loan is None or loan.member != MEMBER:
raise NotFound(
f"No loan '{loan_id}' for you.", hint="Use loans.mine to see your loans."
)
return loan_out(ctx, loan if loan.returned else await ctx.deps.give_back(loan))
Two more things keep writes honest:
- Writes are never retried automatically. If one fails with a transient error, the model is told; it is not silently repeated.
- A write that passes its deadline keeps running in the background and reports
ambiguous_write. Because it is idempotent, calling again returns its result once it finishes instead of writing twice.
Clients that want their own key, such as a host retrying after a network error, pass one in _meta, and it is used instead of the arguments.
Lints for writes¶
| Lint | Catches |
|---|---|
write-without-side-effects |
A write whose description does not say what it changes |
elicit-in-write |
A write that asks the user mid-way, after it may have changed something; use approval= |
input-after-effect |
A tool that asks for input after a write has started |
destructive-without-policy |
An Effect.DESTRUCTIVE tool anyone can call |
Summary¶
- Mark writes
Effect.WRITE; addapproval="required"and apreviewthat says exactly what will happen. idempotency=Truemakes retries safe: the second call replays the first result.- Writes are never retried for you; a write past its deadline is reported as
ambiguous_write. - Use
deps=and abuild()function so tests get fresh state.