Internal tools

Letting AI take actions in your internal tools: an MCP server with confirmation, limits and an audit log

Letting AI take actions in your internal tools: an MCP server with confirmation, limits and an audit log

Most teams start with read-only AI: ask a question, get an answer from your data. We wrote about that in our finance MCP server tutorial. The next request is always the same. “Can it also just do the thing?” Issue the refund, reassign the ticket, extend the trial.

That’s where it gets serious, because now a model is choosing actions that cost money. We built a small support tool for a fictional coffee subscription company, Northbeam, to show the setup we use on client projects: an MCP server where the assistant can look up an order and refund it, but only within the staff member’s limit and only after they confirm. Everything below ran on Node 24 with the official TypeScript SDK (1.32), and the output is copied from the terminal.

How a refund moves through the server

Diagram: Claude and a support agent with her own token call the northbeam-support MCP server. Step 1 find_order is read only. Step 2 prepare_refund checks the limit and what is left to refund, then holds it and returns a code. Step 3 the agent says yes in the chat. Step 4 confirm_refund re-checks inside a transaction and writes the refund and an audit row.
Four steps, and only the last one moves money.

The support agent talks to Claude as usual. When she asks for a refund, the model calls prepare_refund, which checks the order and her limit and stores the refund as pending. Nothing has happened yet. The model shows her the summary, she says yes, and only then does it call confirm_refund with the code it got back.

Why not one refund tool with a “please confirm first” line in its description? Because a description is a request to the model, and models skip steps. With two tools, the server can’t issue a refund that wasn’t prepared first, by the same person, in the last ten minutes.

Doesn’t the client already ask before calling a tool?

Often, yes. The MCP specification says there should always be a human able to deny tool calls, and clients like Claude Desktop ask before running tools. But that prompt is a generic “allow this tool?” dialog, and many people click “always allow” on day one. It also knows nothing about your business rules.

The spec also has elicitation, where the server asks the user a question through the client mid-call. It’s a good fit for confirmation, but client support still varies, so we treat it as a nicer front end on top of the same server-side rules, not a replacement for them. The pattern in this article works in any client.

LayerWhat it stopsCan the model get around it?
Client’s tool approval promptCalls the user didn’t expectNo, but users often turn it off
Tool descriptions (“confirm first”)Nothing on its ownYes
Prepare and confirm toolsRefunds nobody looked atNo, the server enforces the order
Limits checked on the serverRefunds over a person’s authorityNo
Audit log in the same transactionChanges nobody can explain laterNo
Only the last three are controls. The first two are courtesy.

Step 1: Each person gets their own token

A shared API key would make every refund look like it came from “the AI”. Instead, each staff member connects with their own bearer token, and the server turns it into a person with a role and a refund limit. The SDK’s requireBearerAuth middleware calls our verifier and passes the result to every tool as extra.authInfo.

typescript
const verifier = {
  async verifyAccessToken(token: string): Promise<AuthInfo> {
    const staff = db.prepare(`select id, name, email, role, refund_limit_cents, token_expires_at
                               from staff where token_hash = ?`)
      .get(hashToken(token)) as Staff | undefined;
    if (!staff) throw new InvalidTokenError('Unknown token');
    return {
      token, clientId: staff.email, scopes: ['orders:read', 'refunds:write'],
      expiresAt: staff.token_expires_at,  // the SDK rejects tokens without one
      extra: { staff },
    };
  },
};

app.post('/mcp', requireBearerAuth({ verifier }), async (req, res) => {
  const server = buildServer();
  const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
  res.on('close', () => { transport.close(); server.close(); });
  await server.connect(transport);
  await transport.handleRequest(req, res, req.body);
});
Tokens are stored hashed. A fresh server per request keeps one person’s call from leaking into another’s.

In production the token comes from your identity provider through OAuth, which the MCP authorization spec describes in detail, and the staff record is looked up from the token’s subject. The lookup table here keeps the demo self-contained. Everything after this point is the same either way.

Step 2: A tool that checks and holds the refund

prepare_refund does all the checking up front: the order exists, the amount is within this person’s limit, and the order has that much left to refund. If everything passes, it stores a pending row with a short code and a ten-minute expiry. Every outcome, refusals included, goes to the audit log.

typescript
server.registerTool('prepare_refund', {
  title: 'Prepare a refund',
  description: 'Checks a refund and holds it for 10 minutes. Show the summary to the user and ' +
    'only call confirm_refund after they say yes.',
  inputSchema: {
    order_number: z.string().regex(/^NB-\d{5}$/),
    amount: z.number().positive().multipleOf(0.01),
    reason: z.string().min(5).max(200),
  },
  annotations: { readOnlyHint: false, destructiveHint: false },
}, async ({ order_number, amount, reason }, extra) => {
  const staff = extra.authInfo!.extra!.staff as Staff;
  const input = { order_number, amount, reason };
  const cents = Math.round(amount * 100);
  const order = db.prepare(`select * from orders where number = ?`).get(order_number) as any;
  if (!order) { audit(staff, 'prepare_refund', input, 'refused: no such order'); return refused(`No order ${order_number}.`); }

  if (cents > staff.refund_limit_cents) {
    audit(staff, 'prepare_refund', input, 'refused: over staff limit');
    return refused(`${money(cents)} is over your refund limit of ${money(staff.refund_limit_cents)}. Ask a team lead.`);
  }
  const left = order.total_cents - refundedSoFar(order_number);
  if (cents > left) {
    audit(staff, 'prepare_refund', input, 'refused: more than refundable');
    return refused(`Only ${money(left)} of ${order_number} is left to refund.`);
  }

  const code = randomBytes(3).toString('hex').toUpperCase();
  const expires = new Date(Date.now() + 10 * 60_000).toISOString();
  db.prepare(`insert into pending_refunds (code, order_number, amount_cents, reason, staff_id, expires_at)
              values (?, ?, ?, ?, ?, ?)`).run(code, order_number, cents, reason, staff.id, expires);
  audit(staff, 'prepare_refund', input, `held as ${code}`);
  return text(`Ready to refund ${money(cents)} to ${order.customer} for ${order_number} ("${reason}"). ` +
    `Ask the user to confirm. Confirmation code ${code}, valid 10 minutes.`);
});
refused() returns the message with isError: true, so the model sees a clear reason it can pass on.

Refusals are returned as tool errors with a plain sentence rather than thrown. The model reads “$250.00 is over your refund limit of $100.00. Ask a team lead.” and can say exactly that to the agent, instead of guessing at a stack trace.

The reason field is required. It costs the agent five words and saves someone an hour when finance asks why a customer got money back.

Step 3: The only tool that moves money

confirm_refund takes nothing but the code. The amount, order and reason come from the pending row, so the model can’t change them between the summary the person saw and the refund that goes out.

typescript
server.registerTool('confirm_refund', {
  title: 'Confirm a refund',
  description: 'Issues a refund prepared by prepare_refund. Only call this after the user has confirmed.',
  inputSchema: { code: z.string().regex(/^[0-9A-F]{6}$/) },
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
}, async ({ code }, extra) => {
  const staff = extra.authInfo!.extra!.staff as Staff;
  const pending = db.prepare(`select * from pending_refunds where code = ?`).get(code) as any;

  // A code only works for the person who prepared it.
  if (!pending || pending.staff_id !== staff.id) {
    audit(staff, 'confirm_refund', { code }, 'refused: unknown code');
    return refused(`No pending refund ${code} for you.`);
  }
  if (pending.status === 'done') {
    audit(staff, 'confirm_refund', { code }, `repeat call, refund ${pending.refund_id} already issued`);
    return text(`Refund ${code} was already issued (refund #${pending.refund_id}). Nothing changed.`);
  }
  if (pending.expires_at < new Date().toISOString()) {
    audit(staff, 'confirm_refund', { code }, 'refused: expired');
    return refused(`Code ${code} has expired. Prepare the refund again.`);
  }

  db.exec('begin immediate');
  try {
    // Re-check inside the transaction: another refund may have landed since prepare.
    const order = db.prepare(`select total_cents from orders where number = ?`).get(pending.order_number) as any;
    if (pending.amount_cents > order.total_cents - refundedSoFar(pending.order_number)) {
      db.exec('rollback');
      audit(staff, 'confirm_refund', { code }, 'refused: order changed since prepare');
      return refused(`${pending.order_number} changed since this refund was prepared. Prepare it again.`);
    }
    const r = db.prepare(`insert into refunds (order_number, amount_cents, reason, staff_id, created_at)
                          values (?, ?, ?, ?, ?)`)
      .run(pending.order_number, pending.amount_cents, pending.reason, staff.id, new Date().toISOString());
    db.prepare(`update pending_refunds set status = 'done', refund_id = ? where code = ?`).run(r.lastInsertRowid, code);
    audit(staff, 'confirm_refund', { code }, `issued refund ${r.lastInsertRowid}`);
    db.exec('commit');
    return text(`Refunded ${money(pending.amount_cents)} on ${pending.order_number} (refund #${r.lastInsertRowid}).`);
  } catch (err) {
    db.exec('rollback');
    throw err;
  }
});
The refund, the pending row and the audit entry are written in one transaction.

Three things in there are easy to miss. The check runs again inside the transaction, because two people can prepare refunds on the same order a minute apart. A second call with a used code returns the original result instead of refunding twice, which is what idempotentHint promises the client. And destructiveHint: true tells clients this is the call worth asking about.

Step 4: Try to break it

Before connecting a real assistant, we drive the server with the SDK’s own client, playing two staff members: Priya, a support agent with a $100 limit, and Marcus, a team lead with $500. The script lists the tools, runs a normal refund, then tries the things that should fail.

typescript
const priya = await connect('tok_priya_demo');
const marcus = await connect('tok_marcus_demo');

await call(priya, 'priya', 'find_order', { order_number: 'NB-10482' });
const held = await call(priya, 'priya', 'prepare_refund', { order_number: 'NB-10482', amount: 42.5, reason: 'Two bags arrived split' });
const code = held.match(/code ([0-9A-F]{6})/)![1];
await call(marcus, 'marcus', 'confirm_refund', { code });   // someone else's code
await call(priya, 'priya', 'confirm_refund', { code });     // the real confirmation
await call(priya, 'priya', 'confirm_refund', { code });     // a retry
await call(priya, 'priya', 'prepare_refund', { order_number: 'NB-10517', amount: 250, reason: 'Wrong grinder shipped' });
await call(marcus, 'marcus', 'prepare_refund', { order_number: 'NB-10482', amount: 180, reason: 'Customer cancelled plan' });
connect() opens a Streamable HTTP client with that person’s token; call() prints the result.
Terminal output. Tools listed with annotations. Priya finds order NB-10482 for Dana Ortiz, total $189.00. She prepares a $42.50 refund and gets code 4791AD. Marcus tries to confirm 4791AD and is refused. Priya confirms and the refund is issued. A repeat confirm changes nothing. Priya preparing $250 is refused as over her $100 limit. Marcus preparing $180 is refused because only $146.50 is left. A request without a token gets HTTP 401. The audit log lists all seven calls, including refusals.
The real run. Every refusal came from the server, not from the model.

Read the last case closely. Marcus is allowed to refund $180, but the order only has $146.50 left after Priya’s refund. Limits per person and limits per order are separate checks, and you need both.

Which actions to hand over first

Not every write needs this much ceremony. We sort them by how hard they are to undo and how much they cost when wrong.

Kind of actionExamplesWhat we do
Easy to undo, no moneyTag a ticket, assign an owner, add an internal noteOne tool, logged. The client’s normal approval is enough.
Customer can see itSend a reply, change a delivery datePrepare and confirm, so the person reads it first
Money or accessRefunds, credits, plan changes, user rolesPrepare and confirm, limits per person, re-check on confirm
Hard to undo at scaleBulk updates, deleting records, payoutsKeep out of the assistant. Build a screen with a second approver instead.

This sits on top of the internal tool you already have. On a Retool or custom admin app, the MCP server calls the same database or API the screens use, so the rules live in one place and the assistant can’t do anything a person couldn’t do from the app. If you don’t have that tool yet, that’s usually the first project; see our internal tools work.

What shapes the cost

FactorWhy it matters
Number of write actionsEach one needs its own checks, limits and failure tests. Two or three well-chosen actions cover most support work.
Where the rules live todayIf limits already exist in your app or database, the server reuses them. If they live in people’s heads, we write them down first.
IdentityPlugging into your existing SSO is quicker than issuing and rotating tokens by hand.
Systems behind the actionA refund in your own database is simple. A refund through Stripe or Shopify adds their API, retries and webhooks.

Mistakes we’d avoid

Sources

Spotted something out of date? Tell us

Questions we often hear

Can the AI refund more than a person is allowed to?

Not in this design. The limit is stored against the signed-in staff member and checked by the server before anything is held, whatever the model asks for.

Why not use MCP elicitation for the confirmation?

You can, where the client supports it, and it gives a cleaner prompt. We still keep the prepare and confirm tools underneath so the rules hold in every client.

Does this work with ChatGPT and other clients?

Yes. It’s a standard MCP server over Streamable HTTP, so any MCP client that supports remote servers can connect with a staff member’s token.

Can you add this to our existing Retool or custom admin app?

Yes. The server calls the same database or API your app uses. Tell us about it on a free 30-minute call and an engineer will say which actions we’d start with.

Want your team to act from the chat, safely?

Tell us which internal tool your team lives in and the actions they repeat most. On a free 30-minute call an engineer will say which ones we’d hand to an assistant first, and which we wouldn’t.