Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
MCP: save pictures in the chat, paid generations ask, FLUX preset (26h) (#780)
Oleksandr Ivanchenkod5b645bb434a
diff --git a/docs/approvals.md b/docs/approvals.mdindex 80bf3126..05aa3f91 100644--- a/docs/approvals.md+++ b/docs/approvals.md@@ -17,7 +17,10 @@ an install; switch it in Settings when you're ready. While the built-in passwordpasswords, a new space starts on `ask` instead (see below). An unknown bot always asks.Whatever the mode, a call that looks like a payment shows a card, even when `smart` finds it-safe or "Always this session" was given: see [payments.md](payments.md).+safe or "Always this session" was given: see [payments.md](payments.md). That includes paid+generations: a FLUX (Black Forest Labs) or Picsart tool that spends the person's credits asks+every time, and its card says whose credits it uses, without a price. Their reads (a balance, a+job's status) don't ask.Whatever the mode, on a Home Assistant MCP server (it answers `initialize` with `serverInfo.name``home-assistant`), a call that acts on a lock, a door, a garage door, a gate or an alarm shows a@@ -162,6 +165,6 @@ don't count, and a late Allow on an earlier card still runs that call (`src/mcp/## Tests-`cargo test --test smart_approvals_test --test approvals_off_test --test approvals_passwords_test --test payment_floor_test --test home_locks_always_ask_test`+`cargo test --test smart_approvals_test --test approvals_off_test --test approvals_passwords_test --test payment_floor_test --test home_locks_always_ask_test --test mcp_media_test`and the classifier tables in `src/mcp/shell_risk.rs` (`cargo test --lib shell_risk`); a no thatstays a no: `cargo test --lib declined`.diff --git a/docs/mcp-api.md b/docs/mcp-api.mdindex 1120ea34..fbee527d 100644--- a/docs/mcp-api.md+++ b/docs/mcp-api.md@@ -439,6 +439,24 @@ The kwant's reply message stores its MCP calls in `tool_calls` (JSON array, `nul4000 characters. For CLI agents kwnt only sees the approval step, so their records havestatus `allowed` or `denied` and no `result`.+### Pictures and files a tool returns (26h)++A successful call's `image` and `audio` parts and `resource` parts with a `blob` are decoded,+stored and posted in the turn's chat as the bot's file (`meta.kind: "file"`, `auto: true`; the+same bytes again within 10 minutes aren't posted twice). The model and `result` get one line+per file instead of the base64: `Image saved in this chat as flux-generate_image-1.png (id …);+the person sees it there.` The usual caps hold (20 MB, videos and audio 100 MB); the first 10+files of a call are saved and later ones are named as not saved. A file that can't be saved+keeps its `[image: image/png]` stand-in with the reason, and the others still save. A turn with+no chat (a dry run, a routine without one) says the file came back but couldn't be saved.++FLUX (Black Forest Labs) results can also come as expiring links on `delivery*.bfl.ai`. kwnt+downloads those right after the call and puts the saved file (`kwnt-file:<id> (<name>)`) in the+link's place, in the model's text and in `result`. The download is HTTPS only, to that host list+only (kept per app; a redirect off it stops the download), to public addresses only, within 60+seconds and 100 MB. If it fails, the link stays with the reason. Picsart's result links aren't+downloaded yet: their file host isn't on a list.+## Deployment notes- Nothing beyond kwnt itself is required: stdio servers are plain child processes, so whateverdiff --git a/docs/payments.md b/docs/payments.mdindex 759c40eb..3426f8d4 100644--- a/docs/payments.md+++ b/docs/payments.md@@ -29,6 +29,25 @@ every MCP tool, through claude's permission prompt and the MCP gateway), in`search`, …): Stripe, PayPal, Square, Wise, Coinbase, Braintree, Adyen, Revolut, Mollie,Paddle, Lemon Squeezy, Razorpay, GoCardless, Klarna, Venmo, Cash App, Chargebee, Recurly,Payoneer, Checkout.com, Authorize.net, Plaid, MoonPay, Kraken, Binance.+- Paid generations (since 26h): a tool that spends the person's credits on an image and video app.+ The app is known by the server's name or its address, never by the tool name alone, so a+ shop's or a local model's `generate_image` doesn't ask.+ - Black Forest Labs (FLUX): a server named `flux`, `bfl` or `black-forest-labs`, or at+ `mcp.bfl.ai` or any other `*.bfl.ai` address. `generate_image`, `generate_variations`, `vto`,+ `generate_video`, `enhance_video`, `upscale_video`, `edit_video`, and any new tool there that+ doesn't start with a read verb.+ - Picsart: a server named `picsart`, or at `api.picsart.com` or any other `*.picsart.com`+ address. `picsart_generate`, `picsart_remove_bg`, `picsart_change_bg`, `picsart_enhance`,+ `picsart_vectorize`, `picsart_media_contact_sheet` and `picsart_media_export`. Its scene edits+ (`picsart_media_apply_*`) and drive cost nothing and don't ask.+ - Reads never ask: `get_credits`, `get_history`, `get_result`, `list_skills`, `get_skill`,+ `request_upload_url`; `picsart_credits`, `picsart_job_status`, `picsart_list_models`,+ `picsart_model_catalog`, `picsart_model_params`, `picsart_preflight`.++ The card says whose credits the call uses ("This uses your Black Forest Labs credits:+ generate_image", `details.credits`) and never shows a price: kwnt doesn't know it. A server+ someone renamed (say `images` at `mcp.bfl.ai`) is still known by its address, also when an+ agent CLI asks for the call (`credit_floor` looks the bot's server up).- Any other tool whose name has a pay word (`pay`, `payment`, `payout`, `purchase`, `checkout`or `check_out`, `buy`, `charge`, `donate`, …), a money move (`send`/`transfer`/`withdraw` with`money`, `funds`, `cash`, `crypto`, `btc`, `usdc`, `usd`, `stablecoin`, …), or an order step@@ -158,6 +177,7 @@ store's `set_limit {token: "<32-character base58 key>", value: 100}`). That's ac## Tests-`cargo test --test payment_floor_test`, `cargo test --test browser_pay_gate_test` (a real+`cargo test --test payment_floor_test`, `cargo test --test mcp_media_test` (paid generations on+an offline FLUX-shaped server), `cargo test --test browser_pay_gate_test` (a realChrome on local card pages; `-- --ignored` also walks saucedemo.com to "Finish") and the tables in `src/mcp/payment_floor.rs`(`cargo test --lib payment_floor`).diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex 65b59014..91143ac2 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -72,7 +72,7 @@ import type { PointSink } from './PointLayer';import { DropRecipient, FOLDER_NOTE, dragHasFiles, dropAnnouncement, dropCard, leaveMs, modalOpen, previewDrag, splitDrop, windowDragWatch } from '../dragPreview';import { DropBot, DropLayer, DropPhase } from './DropLayer';import { EarlierCopies, FileTiles, PointChip, UploadChip } from './Attachments';-import { arrangeSharedFiles, botDisplayName, botOf, shareInfo } from '../sharedFiles';+import { arrangeSharedFiles, botDisplayName, botOf, madeWithCaption, shareInfo } from '../sharedFiles';import { parseToolNoteMeta } from '../toolNotes';import { ToolFailureLine } from './ToolFailureLine';import { parseToolFailureMeta } from '../toolFailures';@@ -1989,9 +1989,10 @@ export const ChatView: React.FC<ChatViewProps> = ({{files.length > 0 && <FileTiles files={files} align={onYourSide ? 'end' : 'start'} sharedBy={filesOnly && !isUser ? displayName : undefined} at={msg.created_at ?? null} />}{isUser && heldNotes?.[msg.id]}{filesOnly && !isUser && files.length > 0 && shareInfo(msg.meta).auto && (- // P4: kwnt posted the turn's last screenshot because the reply claimed a picture and none was shared+ // P4: kwnt posted the turn's last screenshot because the reply claimed a picture and none was shared.+ // 26h: a file an MCP tool made names the app (its preset label, else the server name as typed).<p data-shared-auto="" className="mt-1 text-[11px] text-zinc-500">- Shared automatically+ {madeWithCaption(shareInfo(msg.meta).madeWith)}</p>)}{olderCopies && olderCopies.length > 0 && (diff --git a/frontend/src/components/ModernApprovalCard.tsx b/frontend/src/components/ModernApprovalCard.tsxindex 744453e3..716c46d0 100644--- a/frontend/src/components/ModernApprovalCard.tsx+++ b/frontend/src/components/ModernApprovalCard.tsx@@ -143,6 +143,15 @@ export const paymentReason = (approval: PendingApproval) => {return why.trim().replace(/[.\s]+$/, '') || 'it looks like paying';};+/**+ * 26h: whose credits a paid generation spends ("Black Forest Labs", "Picsart"), from the server's+ * `details.credits`, or null for any other card. The card never guesses a price.+ */+export const paymentCredits = (approval: PendingApproval) => {+ const who = approval.details?.credits;+ return typeof who === 'string' && who.trim() ? who.trim() : null;+};+/*** Who started a turn, as the card names it after "Started by": the server's raw label* (`details.started_by`) mapped to a name people know (Mira's table, #569). Internal names@@ -303,6 +312,7 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({const waiting = approval.waiting === true;const botName = name ?? mcp?.kwant ?? null;const payment = paymentReason(approval);+ const credits = payment ? paymentCredits(approval) : null;const tier = payment ? null : tierReason(approval.details);const startedBy = payment || tier ? null : startedByNote(approval);const time = localClock(approval.asked_at);@@ -451,10 +461,21 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({<div role="note" className="flex items-start gap-2 mt-2.5 rounded-lg border border-rose-500/30 bg-rose-950/30 px-3 py-2 text-sm leading-5"><CreditCard size={14} className="mt-0.5 shrink-0 text-rose-300" aria-hidden="true" /><div className="min-w-0 space-y-0.5">- <p className="text-rose-100 break-words">- <span className="font-semibold">This looks like a payment:</span> {payment}.- </p>- <p className="text-xs leading-[18px] text-zinc-400">Payments always ask you, even with approvals off. Allowing covers this one payment.</p>+ {credits ? (+ <>+ <p className="text-rose-100 break-words" data-credits>+ <span className="font-semibold">This uses your {credits} credits.</span>+ </p>+ <p className="text-xs leading-[18px] text-zinc-400">Anything that spends credits asks you first, even with approvals off. Allowing covers just this one.</p>+ </>+ ) : (+ <>+ <p className="text-rose-100 break-words">+ <span className="font-semibold">This looks like a payment:</span> {payment}.+ </p>+ <p className="text-xs leading-[18px] text-zinc-400">Payments always ask you, even with approvals off. Allowing covers this one payment.</p>+ </>+ )}</div></div>)}diff --git a/frontend/src/mcp.ts b/frontend/src/mcp.tsindex 77810823..d87ea42c 100644--- a/frontend/src/mcp.ts+++ b/frontend/src/mcp.ts@@ -397,12 +397,26 @@ export const MCP_PRESETS: McpPreset[] = [// Checked 2026-10-24: registration at auth.picsart.com/api/oauth2/register.id: 'picsart',label: 'Picsart',- blurb: 'Generate and edit images and video, remove backgrounds. Sign in after adding.',+ blurb: 'Make and edit images and video, remove backgrounds. Uses your Picsart credits.',category: 'creative',needs: ['Sign-in'],source: 'https://picsart.github.io/picsart-mcp-cli-docs/guide/mcp-quickstart',form: httpPreset('picsart', 'https://api.picsart.com/gen-ai/mcp'),},+ {+ // 26h: Black Forest Labs' hosted FLUX server, sign-in only. Generations, edits and videos use+ // BFL credits, so they always ask (src/mcp/payment_floor.rs); pictures come back as files in the+ // chat. Results can take minutes, hence the longer timeout. Checked 2026-11-17 from its README;+ // not yet tried with a real sign-in.+ id: 'flux',+ label: 'FLUX',+ blurb: 'Make and edit images and video. Uses your Black Forest Labs credits. Sign in after adding.',+ category: 'creative',+ needs: ['Sign-in'],+ source: 'https://github.com/black-forest-labs/flux-mcp',+ form: { ...httpPreset('flux', 'https://mcp.bfl.ai'), timeout_secs: 180 },+ keywords: ['Black Forest Labs', 'bfl', 'image generation'],+ },];/**diff --git a/frontend/src/sharedFiles.ts b/frontend/src/sharedFiles.tsindex 71f222df..83315c17 100644--- a/frontend/src/sharedFiles.ts+++ b/frontend/src/sharedFiles.ts@@ -5,6 +5,7 @@// It never falls back to the chat title: in a space that title is the space ("@booktun.ing").import { isSharedFileMessage, parseAttachments } from './attachments';import { parseMetaObject } from './questions';+import { MCP_PRESETS } from './mcp';/** What a row shows when its bot can't be found (deleted, or the list hasn't loaded yet). */export const UNKNOWN_BOT_LABEL = 'A bot';@@ -45,15 +46,25 @@ export function botDisplayName(senderId: string | undefined | null, bots: Readonexport interface ShareInfo {/** The bot's id from meta, when the server sent it. */kwantId: string | null;- /** True when kwnt shared the turn's last screenshot itself, because the reply claimed a picture. */+ /** True when kwnt shared the file itself: the turn's last screenshot because the reply claimed a picture, or a file an MCP tool returned. */auto: boolean;+ /** 26h: the MCP server whose tool made the file (`meta.made_with`), as the person named it. */+ madeWith: string | null;}/** What a shared-file row's meta says about who shared it and how. */export function shareInfo(meta: string | null | undefined): ShareInfo {const o = parseMetaObject(meta) ?? {};const id = typeof o.kwant_id === 'string' && o.kwant_id ? o.kwant_id : null;- return { kwantId: id, auto: o.auto === true };+ const madeWith = typeof o.made_with === 'string' && o.made_with.trim() ? o.made_with.trim() : null;+ return { kwantId: id, auto: o.auto === true, madeWith };+}++/** The caption under a file kwnt shared itself: "Made with FLUX · saved automatically" for a file an MCP tool made, else "Shared automatically". */+export function madeWithCaption(madeWith: string | null): string {+ if (!madeWith) return 'Shared automatically';+ const label = MCP_PRESETS.find((p) => p.id === madeWith)?.label ?? madeWith;+ return `Made with ${label} · saved automatically`;}/** Who a message is from, for matching: a share's meta.kwant_id when present, else its sender_id. */diff --git a/frontend/tests/approvalCard.test.mjs b/frontend/tests/approvalCard.test.mjsindex 0c335904..06044e8e 100644--- a/frontend/tests/approvalCard.test.mjs+++ b/frontend/tests/approvalCard.test.mjs@@ -80,6 +80,41 @@ test('a payment card says why it is a payment and offers only Allow once and Denassert.match(html, /role="note"/);});+// 26h: a paid generation, shaped like BrokerApprover::classified for a FLUX call.+const fluxTicket = (extra = {}) => ({+ id: 'f1',+ tool_name: 'mcp__flux__generate_image',+ details: {+ source: 'mcp',+ server: 'flux',+ tool: 'generate_image',+ kwant_name: 'Pixel',+ arguments: { prompt: 'a red fox in snow' },+ payment_reason: 'generate_image uses your Black Forest Labs credits',+ credits: 'Black Forest Labs',+ ...extra,+ },+});++test('a paid generation names whose credits it uses, never a price, and offers only Allow once and Deny', () => {+ const html = render(fluxTicket());+ assert.match(html, /This uses your Black Forest Labs credits\.<\/span>/);+ assert.match(html, /Anything that spends credits asks you first, even with approvals off\. Allowing covers just this one\./);+ // The tool stays in the header and details; the credits note itself never names it+ const note = html.match(/<div role="note"[\s\S]*?<\/div><\/div>/)?.[0] ?? '';+ assert.match(note, /Black Forest Labs credits/);+ assert.doesNotMatch(note, /generate_image/);+ assert.doesNotMatch(html, /looks like a payment|\$\d|price/);+ assert.match(html, /Allow once/);+ assert.doesNotMatch(html, /Always allow|Always this session/);+ const picsart = render(fluxTicket({ server: 'picsart', tool: 'picsart_generate', credits: 'Picsart', payment_reason: 'picsart_generate uses your Picsart credits' }));+ assert.match(picsart, /This uses your Picsart credits\.<\/span>/);+ // A credits label without a payment reason is no payment card+ assert.doesNotMatch(render(fluxTicket({ payment_reason: undefined })), /credits\.<\/span>/);+ // A blank label falls back to the payment wording+ assert.match(render(fluxTicket({ credits: ' ' })), /This looks like a payment:/);+});+test('a payment shown as a Claude tool card also drops Always this session', () => {const html = render({id: 'p2',diff --git a/frontend/tests/mcp.test.mjs b/frontend/tests/mcp.test.mjsindex 7c1f8001..695385af 100644--- a/frontend/tests/mcp.test.mjs+++ b/frontend/tests/mcp.test.mjs@@ -197,12 +197,27 @@ test('apps without a usable official server point to Composio instead of an inveassert.ok(ids.includes('gmail'));});-test('the asked-for apps are offered: Cloudflare and Picsart as presets, Gmail via Composio', () => {- for (const id of ['cloudflare', 'picsart']) {+test('the asked-for apps are offered: Cloudflare, Picsart and FLUX as presets, Gmail via Composio', () => {+ for (const id of ['cloudflare', 'picsart', 'flux']) {const p = MCP_PRESETS.find((x) => x.id === id);assert.ok(p && p.needs.includes('Sign-in') && p.form.transport === 'http', id);assert.match(p.source, /^https:\/\//, id);}+ // 26h: FLUX sits right after Picsart in Design & media, names Black Forest Labs credits, and waits for slow generations+ const ids = MCP_PRESETS.map((p) => p.id);+ assert.equal(ids.indexOf('flux'), ids.indexOf('picsart') + 1);+ const flux = MCP_PRESETS.find((p) => p.id === 'flux');+ assert.equal(flux.label, 'FLUX');+ assert.equal(flux.category, 'creative');+ assert.equal(flux.form.name, 'flux');+ assert.equal(flux.form.url, 'https://mcp.bfl.ai');+ assert.equal(flux.form.timeout_secs, 180);+ assert.ok(flux.blurb.length <= 100, flux.blurb);+ assert.match(flux.blurb, /Black Forest Labs credits/);+ assert.doesNotMatch(flux.blurb, /official|partner|endorse|recommended/i);+ for (const q of ['flux', 'FLUX', 'Black Forest']) {+ assert.ok(searchPresets(q).some((p) => p.id === 'flux'), q);+ }assert.deepEqual(searchComposioOnly('gmail').map((a) => a.id), ['gmail']);assert.deepEqual(searchPresets('gmail'), []);});diff --git a/frontend/tests/sharedImages.test.mjs b/frontend/tests/sharedImages.test.mjsindex 1e785012..caded1ff 100644--- a/frontend/tests/sharedImages.test.mjs+++ b/frontend/tests/sharedImages.test.mjs@@ -267,20 +267,26 @@ test("ChatView: in a bot's own chat an id row resolves to that bot even before t// ---- the server's new shape (vega-080-share-screens) ---------------------------------------------const newShare = (id, bot, name, when, auto = false) => ({+const newShare = (id, bot, name, when, auto = false, made_with = undefined) => ({id,sender_role: 'kwant',sender_id: bot.name,text: `Shared a file: ${name}`,created_at: when,- meta: JSON.stringify({ kind: 'file', attachments: [{ id: fileId(), name, mime: 'image/jpeg', size: sizeOf(name) }], kwant_id: bot.id, kwant_name: bot.name, turn_id: 't1', auto }),+ meta: JSON.stringify({ kind: 'file', attachments: [{ id: fileId(), name, mime: 'image/jpeg', size: sizeOf(name) }], kwant_id: bot.id, kwant_name: bot.name, turn_id: 't1', auto, made_with }),});test("shareInfo reads kwant_id and auto; a new-shape share follows its bot's reply", () => {const s = newShare('n1', bots[0], 'screenshot-booktun.ing.jpg', at('11:00'), true);- assert.deepEqual(m.shareInfo(s.meta), { kwantId: FRONTEND, auto: true });- assert.deepEqual(m.shareInfo(null), { kwantId: null, auto: false });- assert.deepEqual(m.shareInfo('{"kind":"file","auto":"yes"}'), { kwantId: null, auto: false }, 'only a real true counts');+ assert.deepEqual(m.shareInfo(s.meta), { kwantId: FRONTEND, auto: true, madeWith: null });+ assert.deepEqual(m.shareInfo(null), { kwantId: null, auto: false, madeWith: null });+ assert.deepEqual(m.shareInfo('{"kind":"file","auto":"yes"}'), { kwantId: null, auto: false, madeWith: null }, 'only a real true counts');+ assert.equal(m.shareInfo('{"kind":"file","auto":true,"made_with":" flux "}').madeWith, 'flux');+ assert.equal(m.shareInfo('{"kind":"file","auto":true,"made_with":" "}').madeWith, null);+ assert.equal(m.madeWithCaption(null), 'Shared automatically');+ assert.equal(m.madeWithCaption('flux'), 'Made with FLUX · saved automatically');+ assert.equal(m.madeWithCaption('picsart'), 'Made with Picsart · saved automatically');+ assert.equal(m.madeWithCaption('images'), 'Made with images · saved automatically');// A share named after its bot, with the id in meta, follows that bot's reply (by id).const msgs = [you('u1', 'show me', at('11:00')), newShare('n2', bots[0], 'screenshot.jpg', at('11:00', 5)), reply('r1', FRONTEND, 'Here it is', at('11:00', 9))];assert.deepEqual(m.arrangeSharedFiles(msgs, bots).messages.map((x) => x.id), ['u1', 'r1', 'n2']);@@ -308,6 +314,23 @@ test('ChatView: a new-shape share shows its bot, and an automatic one says "Sharv.unmount();});+test('ChatView: a picture an MCP tool made names the app: the preset label, else the server name', async () => {+ const msgs = [+ you('u1', 'Make a fox', at('11:20')),+ reply('r1', 'Growth', 'Here it is.', at('11:20', 20)),+ newShare('f1', bots[1], 'flux-generate_image-1.png', at('11:20', 21), true, 'flux'),+ you('u2', 'and another', at('11:21')),+ reply('r2', 'Growth', 'Done.', at('11:21', 20)),+ newShare('f2', bots[1], 'images-generate_image-1.png', at('11:21', 21), true, 'images'),+ ];+ const v = mount(msgs);+ await settle();+ const caption = (id) => v.host.querySelector(`[data-message-id="${id}"] [data-shared-auto]`)?.textContent;+ assert.equal(caption('f1'), 'Made with FLUX · saved automatically');+ assert.equal(caption('f2'), 'Made with images · saved automatically', 'a renamed server shows its name as typed');+ v.unmount();+});+// ---- the running turn (Mira: no jump) -----------------------------------------------------------test("arrange: while a bot's turn runs, its loose shares go to the live row; others' stay", () => {diff --git a/src/drivers/api.rs b/src/drivers/api.rsindex 97e0720f..85d1e509 100644--- a/src/drivers/api.rs+++ b/src/drivers/api.rs@@ -2162,6 +2162,7 @@ mod tests {approvals: crate::mcp::Approvals::Ask,records: Default::default(),kwnt_only: false,+ media: None,});match driver.stream_turn(input, tx).await {Err(DriverError::Execution(why)) => assert!(why.contains("MCP servers"), "{why}"),@@ -2328,6 +2329,7 @@ mod tests {approvals: crate::mcp::Approvals::Off,records: Default::default(),kwnt_only: false,+ media: None,});input.delivery = Some(crate::router::delivery::keyword_plan(complaint, &[]));driver.stream_turn(input, tx).await.unwrap();diff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex 904fd0e5..f262156e 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -1583,6 +1583,8 @@ impl Driver for CliDriver {let mut _mcp_config: Option<crate::mcp::cli_config::ConfigFile> = None;// 21d: the curl config claude's repeat-guard hooks post through; lives as long as the CLIlet mut repeat_hook: Option<crate::mcp::cli_config::ConfigFile> = None;+ // 26h D3: which hooks that config serves (claude's own tools; the bot's MCP tools' files)+ let (mut builtins_hook, mut media_hook) = (false, false);// Whether this computer's `--settings` already went in (claude: before its prompt)let mut settings_added = false;@@ -1832,7 +1834,14 @@ impl Driver for CliDriver {// repeat guard, which refuses the 4th identical failing call. Only on this// computer: a VM turn's claude gets none of these settingslet builtins = !input.no_tools && !ctx.kwnt_only;- if let (true, true, Some(url)) = (file.is_some(), builtins, ctx.permission_url.as_deref()) {+ // 26h D3: and the bot's own MCP tools hand their files to kwnt, which+ // saves them in the chat (claude calls those servers itself)+ let media = !input.no_tools+ && ctx.media.is_some()+ && ctx.servers.iter().any(|s| crate::mcp::cli_hooks::saves_media_for(&s.name));+ media_hook = media;+ builtins_hook = builtins;+ if let (true, true, Some(url)) = (file.is_some(), builtins || media, ctx.permission_url.as_deref()) {match crate::mcp::cli_hooks::write_curl_config(&ctx.config_dir, url) {Ok(f) => repeat_hook = Some(f),Err(e) => tracing::warn!(error = %e, "couldn't write the repeat guard's hook config; claude's own tools run unguarded"),@@ -1863,7 +1872,7 @@ impl Driver for CliDriver {let mut settings = self.local_settings_args(cfg!(target_os = "macos"));if let Some(hook) = &repeat_hook {// 21d: in the same one `--settings`, joined with any hooks already there- super::mac_local::merge_settings_arg(&mut settings, crate::mcp::cli_hooks::settings(&hook.path));+ super::mac_local::merge_settings_arg(&mut settings, crate::mcp::cli_hooks::settings(&hook.path, builtins_hook, media_hook));}cmd.args(settings);settings_added = true;@@ -2720,6 +2729,7 @@ endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & \"%_prog%\" \"%dp0%\\napprovals: crate::mcp::Approvals::Ask,records: Default::default(),kwnt_only: false,+ media: None,}}diff --git a/src/drivers/mac_local.rs b/src/drivers/mac_local.rsindex b1ad96da..48762219 100644--- a/src/drivers/mac_local.rs+++ b/src/drivers/mac_local.rs@@ -405,7 +405,7 @@ mod tests {fn hooks_merge_per_event_into_the_one_settings() {let mine = json!({"matcher": "Bash", "hooks": [{"type": "command", "command": "mine"}]});let mut args = vec!["--settings".to_string(), json!({ "env": { "A": "1" }, "hooks": { "PreToolUse": [mine], "Stop": [] } }).to_string()];- let guard = crate::mcp::cli_hooks::settings(std::path::Path::new("/d/claude-hook-1.curl"));+ let guard = crate::mcp::cli_hooks::settings(std::path::Path::new("/d/claude-hook-1.curl"), true, false);merge_settings_arg(&mut args, guard.clone());merge_settings_arg(&mut args, settings(&places(), true, None));assert_eq!(args.iter().filter(|a| *a == "--settings").count(), 1, "{args:?}");diff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex 1d8723d5..70078b7b 100644--- a/src/drivers/mod.rs+++ b/src/drivers/mod.rs@@ -1354,6 +1354,7 @@ pub(crate) mod tests {approvals,records: Default::default(),kwnt_only: false,+ media: None,});i}diff --git a/src/main.rs b/src/main.rsindex 90b4b237..fd30c1cd 100644--- a/src/main.rs+++ b/src/main.rs@@ -103,6 +103,9 @@ pub enum Commands {/// Also serve Home Assistant-shaped tools (intent__HassTurnOff and the rest)#[arg(long)]home_tools: bool,+ /// Also serve FLUX-shaped tools that return pictures (generate_image and the rest)+ #[arg(long)]+ media_tools: bool,},/// Run an OAuth-protected mock MCP server over HTTP (for tests and smoke checks)@@ -122,9 +125,9 @@ pub enum Commands {async fn main() -> Result<(), Box<dyn std::error::Error>> {let cli = Cli::parse();// Before logging starts: stdout carries the MCP protocol- if let Some(Commands::McpEchoServer { server_name, home_tools }) = &cli.command {+ if let Some(Commands::McpEchoServer { server_name, home_tools, media_tools }) = &cli.command {// A test helper that holds nothing: left dumpable so tests can find it by its environment- kwnt::mcp::echo_server::run_stdio(server_name.as_deref(), *home_tools).await?;+ kwnt::mcp::echo_server::run_stdio(server_name.as_deref(), *home_tools, *media_tools).await?;return Ok(());}kwnt::harden_process();diff --git a/src/mcp/cli_hooks.rs b/src/mcp/cli_hooks.rsindex e373cbac..139c8719 100644--- a/src/mcp/cli_hooks.rs+++ b/src/mcp/cli_hooks.rs@@ -14,6 +14,13 @@//! - `PostToolUseFailure` (a call that failed, with its `error` text, e.g. `"Exit code 1\n…"`)//! counts one more identical failure. A call claude or the person denied fires neither event.//!+//! 26h D3: claude also calls the bot's own MCP servers itself (`--mcp-config`), so kwnt never sees+//! their results either. With a chat to save files in, one more `PostToolUse` hook for `mcp__…`+//! tools posts the result; kwnt saves its pictures, audio and video in the chat (and FLUX's+//! delivery links, [`super::media::finish_claude`]) and answers `updatedMCPToolOutput`, so the+//! model reads "Image saved in this chat as …" instead of the base64. That hook waits longer+//! ([`MEDIA_HOOK_SECS`]): a delivery download may take up to a minute.+//!//! The hook never blocks a turn on its own error: `curl -sf -m 2 … || true` exits 0 with no output//! when kwnt is unreachable, slow, or answers with an error, and claude then runs the call as usual.//! The URL (it carries the turn's token) sits in a 0600 curl config file, never in argv.@@ -35,6 +42,19 @@ pub const BUILTIN_MATCHER: &str = "^(?!mcp__)";/// Seconds claude waits for the hook before it runs the call anyway (curl itself gives up after 2).const HOOK_TIMEOUT_SECS: u64 = 5;+/// 26h D3: the bot's MCP servers' tools, not kwnt's own (its permission server, `kwnt`, and its+/// tools for the bot, `kwnt_tools`, whose results kwnt already made).+pub const MCP_MATCHER: &str = "^mcp__(?!kwnt(?:_tools)?__)";++/// 26h D3: whether a server's tool results go through the media hook: every server but kwnt's own.+pub fn saves_media_for(server: &str) -> bool {+ !server.eq_ignore_ascii_case(super::RESERVED_SERVER_NAME) && !server.eq_ignore_ascii_case(super::SELF_SERVER_NAME)+}++/// 26h D3: how long the media hook's curl waits for kwnt (a delivery download takes up to 60 s);+/// claude waits 5 s more. Past it the call goes on with claude's own output, nothing saved.+pub const MEDIA_HOOK_SECS: u64 = 90;+/// Where the hooks post for the turn whose permission endpoint is `permission_url`.pub fn hook_url(permission_url: &str) -> String {format!("{}/hook", permission_url.trim_end_matches('/'))@@ -47,25 +67,77 @@ fn sh_quote(s: &str) -> String {/// The hook command: posts claude's payload (stdin) to the URL in `curl_config`. Silent and/// exit 0 whatever happens, so a failure never blocks the call (exit 2 would).pub fn hook_command(curl_config: &Path) -> String {+ hook_command_for(curl_config, 2)+}++/// [`hook_command`], with curl giving up after `secs`.+pub fn hook_command_for(curl_config: &Path, secs: u64) -> String {format!(- "curl -sf -m 2 -H 'Content-Type: application/json' --data-binary @- -K {} || true",+ "curl -sf -m {secs} -H 'Content-Type: application/json' --data-binary @- -K {} || true",sh_quote(&curl_config.to_string_lossy()))}-/// The `hooks` object merged into the turn's one `--settings`.-pub fn settings(curl_config: &Path) -> Value {- let entry = json!([{+/// The `hooks` object merged into the turn's one `--settings`: the repeat guard's hooks for+/// claude's own tools (`builtins`), and 26h's media hook for the bot's MCP tools (`media`).+pub fn settings(curl_config: &Path, builtins: bool, media: bool) -> Value {+ let entry = json!({"matcher": BUILTIN_MATCHER,"hooks": [{"type": "command", "command": hook_command(curl_config), "timeout": HOOK_TIMEOUT_SECS}],- }]);+ });let mut hooks = serde_json::Map::new();- for event in HOOK_EVENTS {- hooks.insert(event.to_string(), entry.clone());+ if builtins {+ for event in HOOK_EVENTS {+ hooks.insert(event.to_string(), json!([entry.clone()]));+ }+ }+ if media {+ let media_entry = json!({+ "matcher": MCP_MATCHER,+ "hooks": [{"type": "command", "command": hook_command_for(curl_config, MEDIA_HOOK_SECS), "timeout": MEDIA_HOOK_SECS + 5}],+ });+ match hooks.get_mut("PostToolUse") {+ Some(Value::Array(list)) => list.push(media_entry),+ _ => {+ hooks.insert("PostToolUse".to_string(), json!([media_entry]));+ }+ }}json!({ "hooks": hooks })}+/// 26h D3: the server and tool of a PostToolUse payload for one of the bot's MCP tools+/// (`mcp__<server>__<tool>`; a server name never holds `__`). `None` for anything else.+pub fn mcp_call(msg: &Value) -> Option<(&str, &str)> {+ if msg["hook_event_name"] != "PostToolUse" {+ return None;+ }+ let (server, tool) = msg["tool_name"].as_str()?.strip_prefix("mcp__")?.split_once("__")?;+ (!server.is_empty() && !tool.is_empty()).then_some((server, tool))+}++/// 26h D3: the folder claude keeps this session's saved tool output in: next to the transcript+/// (`<dir>/<session_id>.jsonl`), `<dir>/<session_id>/tool-results`. `None` when the payload+/// doesn't say, or the transcript isn't named for the session.+pub fn tool_results_dir(msg: &Value) -> Option<PathBuf> {+ let session = msg["session_id"].as_str().filter(|s| !s.is_empty() && !s.contains(['/', '\\', '.']))?;+ let transcript = Path::new(msg["transcript_path"].as_str()?);+ if transcript.file_name()?.to_str()? != format!("{session}.jsonl") {+ return None;+ }+ Some(transcript.parent()?.join(session).join("tool-results"))+}++/// 26h D3: the PostToolUse answer that gives the model `text` instead of the tool's own output.+pub fn replace_output(text: &str) -> Value {+ json!({+ "hookSpecificOutput": {+ "hookEventName": "PostToolUse",+ "updatedMCPToolOutput": [{"type": "text", "text": text}],+ }+ })+}+/// Writes the curl config (`url = "…"`, mode 0600) for this turn's hooks next to its MCP config./// Removed when the returned guard drops.pub fn write_curl_config(config_dir: &Path, permission_url: &str) -> std::io::Result<ConfigFile> {@@ -494,7 +566,7 @@ mod tests {#[test]fn settings_post_three_events_for_builtin_tools_and_fail_open() {let path = Path::new("/Users/o/Library/Application Support/kwnt/mcp/claude-hook-1.curl");- let v = settings(path);+ let v = settings(path, true, false);let hooks = v["hooks"].as_object().unwrap();assert_eq!(hooks.len(), 3);for event in HOOK_EVENTS {@@ -528,4 +600,61 @@ mod tests {drop(f);assert!(!path.exists());}++ #[test]+ fn the_media_hook_posts_mcp_results_and_waits_longer() {+ let path = Path::new("/d/mcp/claude-hook-1.curl");+ let both = settings(path, true, true);+ let post = both["hooks"]["PostToolUse"].as_array().unwrap();+ assert_eq!(post.len(), 2, "the repeat guard's entry and the media entry: {post:?}");+ assert_eq!(post[0]["matcher"], BUILTIN_MATCHER);+ assert_eq!(post[1]["matcher"], MCP_MATCHER);+ let h = &post[1]["hooks"][0];+ assert_eq!(h["timeout"], MEDIA_HOOK_SECS + 5);+ let cmd = h["command"].as_str().unwrap();+ assert!(cmd.starts_with(&format!("curl -sf -m {MEDIA_HOOK_SECS} ")), "{cmd}");+ assert!(cmd.ends_with(" || true"), "{cmd}");+ assert_eq!(both["hooks"]["PreToolUse"].as_array().unwrap().len(), 1, "media only after the call");+ // A turn whose builtins aren't guarded still gets the media hook alone+ let media = settings(path, false, true);+ assert_eq!(media["hooks"].as_object().unwrap().len(), 1);+ assert_eq!(media["hooks"]["PostToolUse"][0]["matcher"], MCP_MATCHER);+ assert_eq!(settings(path, false, false)["hooks"], json!({}));+ }++ #[test]+ fn mcp_calls_and_the_sessions_tool_results_folder_come_from_the_payload() {+ // Recorded from claude 2.1.326 (Nov 17), the image trimmed+ let msg = json!({"session_id": "1e0695b0-0780-4de2-8bde-9303851e57f9",+ "transcript_path": "/home/o/.claude/projects/-w/1e0695b0-0780-4de2-8bde-9303851e57f9.jsonl",+ "hook_event_name": "PostToolUse", "tool_name": "mcp__flux__generate_image", "tool_input": {},+ "tool_response": [{"type": "text", "text": "Here is your picture."}],+ "tool_use_id": "toolu_01", "mcp_server": {"name": "flux", "source": "dynamic"}});+ assert_eq!(mcp_call(&msg), Some(("flux", "generate_image")));+ assert_eq!(+ tool_results_dir(&msg).unwrap(),+ Path::new("/home/o/.claude/projects/-w/1e0695b0-0780-4de2-8bde-9303851e57f9/tool-results")+ );+ let mut other = msg.clone();+ other["hook_event_name"] = json!("PreToolUse");+ assert_eq!(mcp_call(&other), None);+ other = msg.clone();+ other["tool_name"] = json!("Bash");+ assert_eq!(mcp_call(&other), None);+ // A transcript that isn't the session's, or a session id that walks out, gives no folder+ other = msg.clone();+ other["transcript_path"] = json!("/home/o/.claude/projects/-w/other.jsonl");+ assert_eq!(tool_results_dir(&other), None);+ other = msg.clone();+ other["session_id"] = json!("../x");+ other["transcript_path"] = json!("/home/o/../x.jsonl");+ assert_eq!(tool_results_dir(&other), None);+ let out = replace_output("Image saved in this chat as flux-generate_image-1.png (id a1); the person sees it there.");+ assert_eq!(out["hookSpecificOutput"]["hookEventName"], "PostToolUse");+ assert_eq!(out["hookSpecificOutput"]["updatedMCPToolOutput"][0]["type"], "text");+ // The media hook's matcher leaves kwnt's own permission server alone (claude's regexes are JavaScript's)+ assert_eq!(MCP_MATCHER, "^mcp__(?!kwnt(?:_tools)?__)");+ assert!(saves_media_for("flux") && saves_media_for("kwnt-images"));+ assert!(!saves_media_for("kwnt") && !saves_media_for("kwnt_tools"));+ }}diff --git a/src/mcp/client.rs b/src/mcp/client.rsindex 944310f5..8eca2140 100644--- a/src/mcp/client.rs+++ b/src/mcp/client.rs@@ -61,6 +61,9 @@ pub struct McpTool {pub struct ToolCallResult {pub text: String,pub is_error: bool,+ /// 26h: the whole `tools/call` result, so the caller can save the files in it+ /// ([`super::media`]); `text` stands each of them in as `[image: <mime>]`.+ pub raw: Value,}/// One `tools/list` entry, or `None` when it has no name.@@ -126,8 +129,18 @@ fn response_id(msg: &Value) -> Option<i64> {/// Text an agent can read from a `tools/call` result.fn result_text(result: &Value) -> String {+ result_text_with(result, |_| None)+}++/// [`result_text`], with `instead(i)` standing in for the `i`th content part when it gives a line+/// (26h: what became of a picture kwnt saved).+pub(crate) fn result_text_with(result: &Value, instead: impl Fn(usize) -> Option<String>) -> String {let mut parts = Vec::new();- for item in result["content"].as_array().into_iter().flatten() {+ for (i, item) in result["content"].as_array().into_iter().flatten().enumerate() {+ if let Some(line) = instead(i) {+ parts.push(line);+ continue;+ }match item["type"].as_str().unwrap_or("") {"text" => parts.push(item["text"].as_str().unwrap_or("").to_string()),"image" => parts.push(format!("[image: {}]", item["mimeType"].as_str().unwrap_or("?"))),@@ -341,6 +354,7 @@ impl McpClient {Ok(ToolCallResult {text: result_text(&result),is_error: result["isError"].as_bool().unwrap_or(false),+ raw: result,})}diff --git a/src/mcp/echo_server.rs b/src/mcp/echo_server.rsindex 5dcd246a..0f36664b 100644--- a/src/mcp/echo_server.rs+++ b/src/mcp/echo_server.rs@@ -15,6 +15,12 @@//! tester's install, where switches are lights.//! `--server-name home-assistant` makes the server say it is Home Assistant's; it says//! `kwnt-echo` otherwise.+//!+//! `--media-tools` adds FLUX-shaped tools (26h), all offline: `generate_image {count, prompt}`+//! answers with `count` (default 1, at most 12) small PNG pictures as `image` parts after a text+//! part; `get_credits` (read-only) answers with a balance; `get_result {url}` answers with a+//! delivery-style `{"status": "Ready", "result": {"sample": url}}`. Run it with+//! `--server-name flux` (and name the server `flux`) to look like Black Forest Labs' app.use serde_json::{json, Value};use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};@@ -60,6 +66,60 @@ fn home_tools_list() -> Vec<Value> {.unwrap_or_default()}+fn media_tools_list() -> Vec<Value> {+ let obj = |props: Value| json!({"type": "object", "properties": props});+ json!([+ {"name": "generate_image", "description": "Makes pictures from a prompt (offline stand-in).",+ "inputSchema": obj(json!({"prompt": {"type": "string"}, "count": {"type": "integer"}}))},+ {"name": "get_credits", "description": "Reads the credit balance.",+ "inputSchema": obj(json!({})), "annotations": {"readOnlyHint": true}},+ {"name": "get_result", "description": "Reads a finished generation.",+ "inputSchema": obj(json!({"url": {"type": "string"}})), "annotations": {"readOnlyHint": true}},+ ])+ .as_array()+ .cloned()+ .unwrap_or_default()+}++/// A 96×96 PNG: a diagonal gradient whose colours turn with `n`, so every picture differs.+pub fn sample_png(n: u8) -> Vec<u8> {+ const SIDE: u32 = 96;+ let mut raw = Vec::with_capacity(((SIDE * 3 + 1) * SIDE) as usize);+ for y in 0..SIDE {+ raw.push(0); // no filter+ for x in 0..SIDE {+ let t = ((x + y) * 255 / (2 * SIDE - 2)) as u8;+ let (r, g, b) = match n % 3 {+ 0 => (116u8, 91u8.saturating_add(t / 2), 239u8.saturating_sub(t / 3)),+ 1 => (t, 120, 255 - t),+ _ => (255 - t / 2, 180u8.saturating_sub(t / 2), t),+ };+ raw.extend_from_slice(&[r, g, b]);+ }+ }+ let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());+ std::io::Write::write_all(&mut z, &raw).ok();+ let idat = z.finish().unwrap_or_default();+ let chunk = |out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]| {+ out.extend_from_slice(&(data.len() as u32).to_be_bytes());+ let mut crc = flate2::Crc::new();+ crc.update(kind);+ crc.update(data);+ out.extend_from_slice(kind);+ out.extend_from_slice(data);+ out.extend_from_slice(&crc.sum().to_be_bytes());+ };+ let mut ihdr = Vec::new();+ ihdr.extend_from_slice(&SIDE.to_be_bytes());+ ihdr.extend_from_slice(&SIDE.to_be_bytes());+ ihdr.extend_from_slice(&[8, 2, 0, 0, 0]); // 8-bit RGB+ let mut png = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];+ chunk(&mut png, b"IHDR", &ihdr);+ chunk(&mut png, b"IDAT", &idat);+ chunk(&mut png, b"IEND", &[]);+ png+}+/// The home `GetLiveContext` reads (27e): name, domain, area and state.const HOME: &[(&str, &str, &str, &str)] = &[("Living room lamp", "light", "Living room", "off"),@@ -132,6 +192,18 @@ async fn call(name: &str, args: &Value) -> Value {}}"peek" => text_result("21.4".into(), false),+ "generate_image" => {+ use base64::Engine;+ let count = args["count"].as_u64().unwrap_or(1).clamp(1, 12) as u8;+ let mut content = vec![json!({"type": "text", "text": format!("Generated {count} image(s) for: {}", args["prompt"].as_str().unwrap_or(""))})];+ for n in 0..count {+ let data = base64::engine::general_purpose::STANDARD.encode(sample_png(n));+ content.push(json!({"type": "image", "mimeType": "image/png", "data": data}));+ }+ json!({"content": content, "isError": false})+ }+ "get_credits" => text_result("{\"credits\": 412.5}".into(), false),+ "get_result" => text_result(json!({"status": "Ready", "result": {"sample": args["url"]}}).to_string(), false),"crash" => {eprintln!("mcp-echo-server: crashing on request");std::process::exit(3);@@ -141,14 +213,18 @@ async fn call(name: &str, args: &Value) -> Value {}/// Serves MCP on stdin/stdout until stdin closes, saying it is `server_name` (default-/// `kwnt-echo`), with the Home Assistant-shaped tools too when `home_tools`.-pub async fn run_stdio(server_name: Option<&str>, home_tools: bool) -> std::io::Result<()> {+/// `kwnt-echo`), with the Home Assistant-shaped tools too when `home_tools` and the FLUX-shaped+/// ones when `media_tools`.+pub async fn run_stdio(server_name: Option<&str>, home_tools: bool, media_tools: bool) -> std::io::Result<()> {let server_name = server_name.unwrap_or("kwnt-echo");let listed = {let mut all = tools();if home_tools {all.as_array_mut().unwrap().extend(home_tools_list());}+ if media_tools {+ all.as_array_mut().unwrap().extend(media_tools_list());+ }all};let mut lines = BufReader::new(tokio::io::stdin()).lines();diff --git a/src/mcp/media.rs b/src/mcp/media.rsnew file mode 100644index 00000000..a075145e--- /dev/null+++ b/src/mcp/media.rs@@ -0,0 +1,897 @@+//! 26h: pictures, audio and video an MCP tool returns are saved and shown in the turn's chat as+//! the bot's files, instead of reaching nobody as `[image: image/png]`.+//!+//! [`finish`] runs on every successful call kwnt makes itself ([`super::session::McpToolSession`],+//! so API engines and the CLI gateway both get it):+//! - `image` and `audio` parts and `resource` parts with a `blob` are decoded, stored and posted+//! through the turn's [`MediaSink`] (the bot's file share: sha256 dedupe, the 20 MB / 100 MB+//! caps). The model gets one line per file ("Image saved in this chat as … (id …)"), never the+//! base64.+//! - Expiring delivery links (FLUX's `https://delivery-….bfl.ai/…`) are downloaded right away,+//! saved the same way, and the link in the text is replaced by the saved file. The download is+//! an SSRF boundary: HTTPS only, only the app's allowlisted hosts (a redirect off the list+//! stops it), public addresses only, a time limit and a size cap ([`DeliveryRule`]).+//!+//! At most [`MAX_FILES_PER_CALL`] files are saved per call; later ones are named as skipped. A+//! file that can't be saved keeps its stand-in with the reason, and the others still save.++use super::client::{result_text_with, ToolCallResult};+use super::payment_floor::CreditApp;+use async_trait::async_trait;+use base64::Engine;+use serde_json::Value;+use std::collections::HashMap;+use std::net::SocketAddr;+use std::time::Duration;++/// Most files one call saves (the chat's per-message attachment limit).+pub const MAX_FILES_PER_CALL: usize = crate::server::attachments::MAX_ATTACHMENTS_PER_MESSAGE;+/// Largest file decoded or downloaded: the store's cap for videos and audio. The store then holds+/// everything else to 20 MB.+pub const MAX_FILE_BYTES: usize = crate::server::attachments::MAX_VIDEO_BYTES as usize;+/// Longest a delivery download may take, start to last byte.+const DOWNLOAD_SECS: u64 = 60;+/// Redirects a delivery download follows, each one checked against the allowlist.+const MAX_REDIRECTS: usize = 3;++/// A file [`MediaSink::save`] posted in the chat.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct SavedFile {+ pub id: String,+ pub name: String,+ /// The bot shared these exact bytes in this chat a few minutes ago: that file, not posted again.+ pub already: bool,+}++/// Where a turn's tool files go: the server stores them and posts each as the bot's file share.+#[async_trait]+pub trait MediaSink: Send + Sync {+ /// Stores `bytes` named `name` and posts it in the turn's chat, saying it was made with the+ /// MCP server `server`. `Err` says why not, as a clause people read ("the image is larger+ /// than 20 MB").+ async fn save(&self, bytes: Vec<u8>, name: &str, server: &str) -> Result<SavedFile, String>;+}++/// Hosts a delivery link may be on: `suffix` (`.bfl.ai`) with a first label starting with+/// `label_prefix` (`delivery`, so `delivery-eu1.bfl.ai` and `delivery.eu.bfl.ai`).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct HostPattern {+ pub suffix: &'static str,+ pub label_prefix: &'static str,+}++impl HostPattern {+ fn matches(&self, host: &str) -> bool {+ let host = host.trim_end_matches('.').to_ascii_lowercase();+ let Some(rest) = host.strip_suffix(self.suffix) else { return false };+ let first = rest.split('.').next().unwrap_or("");+ !rest.is_empty() && first.starts_with(self.label_prefix)+ }+}++/// Which links of one app kwnt downloads, and how. Kept per app (preset), so another app's file+/// host (Picsart's CDN, if its results come as links) can join with its own list.+#[derive(Debug, Clone)]+pub struct DeliveryRule {+ hosts: Vec<HostPattern>,+ /// Off only in this module's tests, which serve plain http on 127.0.0.1.+ https_only: bool,+ public_only: bool,+}++impl DeliveryRule {+ /// The delivery hosts of `app`; `None` when its results aren't fetched from links.+ pub fn for_app(app: CreditApp) -> Option<Self> {+ let hosts = match app {+ // BFL's results: https://delivery-eu1.bfl.ai/results/…?se=…&sig=… (signed, expiring)+ CreditApp::Bfl => vec![HostPattern { suffix: ".bfl.ai", label_prefix: "delivery" }],+ // Picsart's results are links too, but on a CDN not checked yet: not fetched+ CreditApp::Picsart => return None,+ };+ Some(Self { hosts, https_only: true, public_only: true })+ }++ /// Whether kwnt may fetch `url`: https, no user or password, the default port, an+ /// allowlisted host name (never an IP address).+ pub fn allows(&self, url: &reqwest::Url) -> bool {+ if self.https_only && (url.scheme() != "https" || url.port().is_some()) {+ return false;+ }+ if !self.https_only && !matches!(url.scheme(), "https" | "http") {+ return false;+ }+ if !url.username().is_empty() || url.password().is_some() {+ return false;+ }+ match url.host() {+ Some(url::Host::Domain(d)) => self.hosts.iter().any(|h| h.matches(d)),+ Some(url::Host::Ipv4(ip)) if !self.public_only => self.hosts.iter().any(|h| h.suffix == ip.to_string()),+ _ => false,+ }+ }++ fn client(&self) -> reqwest::Client {+ let rule = self.clone();+ let policy = reqwest::redirect::Policy::custom(move |attempt| {+ if attempt.previous().len() > MAX_REDIRECTS {+ attempt.error("too many redirects")+ } else if rule.allows(attempt.url()) {+ attempt.follow()+ } else {+ attempt.error("it redirects off the app's file hosts")+ }+ });+ let mut b = reqwest::Client::builder()+ .redirect(policy)+ .timeout(Duration::from_secs(DOWNLOAD_SECS))+ .connect_timeout(Duration::from_secs(10))+ .no_proxy();+ if self.public_only {+ b = b.dns_resolver(std::sync::Arc::new(PublicOnly)).https_only(true);+ }+ b.build().unwrap_or_default()+ }+}++/// Resolves delivery hosts and keeps only public addresses: an allowlisted name pointed into this+/// network is never connected to.+struct PublicOnly;++impl reqwest::dns::Resolve for PublicOnly {+ fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {+ let host = name.as_str().to_string();+ Box::pin(async move {+ let addrs: Vec<SocketAddr> = tokio::net::lookup_host((host.as_str(), 0))+ .await?+ .filter(|a| crate::server::push::is_public_ip(a.ip()))+ .collect();+ if addrs.is_empty() {+ return Err("the file host doesn't resolve to a public address".into());+ }+ Ok(Box::new(addrs.into_iter()) as reqwest::dns::Addrs)+ })+ }+}++/// Downloads `url` under `rule`, at most [`MAX_FILE_BYTES`]. `Err` says why not.+async fn download(rule: &DeliveryRule, url: &reqwest::Url) -> Result<Vec<u8>, String> {+ if !rule.allows(url) {+ return Err("its address isn't one of the app's file hosts".into());+ }+ let mut res = rule.client().get(url.clone()).send().await.map_err(|e| {+ if e.is_redirect() {+ "it redirects off the app's file hosts".to_string()+ } else if e.is_timeout() {+ "the download took too long".to_string()+ } else {+ "the download failed".to_string()+ }+ })?;+ if !res.status().is_success() {+ return Err(format!("the file host answered {}", res.status().as_u16()));+ }+ if res.content_length().is_some_and(|n| n > MAX_FILE_BYTES as u64) {+ return Err("it is larger than 100 MB".into());+ }+ let mut bytes = Vec::new();+ loop {+ match res.chunk().await {+ Ok(Some(chunk)) => {+ if bytes.len() + chunk.len() > MAX_FILE_BYTES {+ return Err("it is larger than 100 MB".into());+ }+ bytes.extend_from_slice(&chunk);+ }+ Ok(None) => return Ok(bytes),+ Err(e) if e.is_timeout() => return Err("the download took too long".into()),+ Err(_) => return Err("the download failed".into()),+ }+ }+}++/// A file inside a result part: its declared type and its base64 bytes.+struct FilePart<'a> {+ mime: &'a str,+ data: &'a str,+}++fn file_part(item: &Value) -> Option<FilePart<'_>> {+ match item["type"].as_str()? {+ "image" | "audio" => Some(FilePart { mime: item["mimeType"].as_str().unwrap_or("?"), data: item["data"].as_str()? }),+ "resource" => Some(FilePart {+ mime: item["resource"]["mimeType"].as_str().unwrap_or("application/octet-stream"),+ data: item["resource"]["blob"].as_str()?,+ }),+ _ => None,+ }+}++/// "Image", "Audio file", "Video" or "File", for a type.+fn noun(mime: &str) -> &'static str {+ match mime.split('/').next().unwrap_or("") {+ "image" => "Image",+ "audio" => "Audio file",+ "video" => "Video",+ _ => "File",+ }+}++fn extension(mime: &str) -> &'static str {+ match mime {+ "image/png" => "png",+ "image/jpeg" | "image/jpg" => "jpg",+ "image/gif" => "gif",+ "image/webp" => "webp",+ "video/mp4" => "mp4",+ "video/quicktime" => "mov",+ "video/webm" => "webm",+ "audio/mpeg" | "audio/mp3" => "mp3",+ "audio/mp4" | "audio/m4a" => "m4a",+ "audio/aac" => "aac",+ "audio/wav" | "audio/x-wav" => "wav",+ "audio/ogg" => "ogg",+ "audio/flac" => "flac",+ "application/pdf" => "pdf",+ _ => "bin",+ }+}++/// The type the bytes prove, else the declared one.+fn real_mime<'a>(bytes: &[u8], declared: &'a str) -> &'a str {+ crate::server::attachments::sniff_magic(&bytes[..bytes.len().min(16)]).unwrap_or(declared)+}++/// The file's name in the chat: `<server>-<tool>-<n>.<ext>`, letters, digits, `-` and `_` only,+/// so it can stand inside the model's JSON text.+fn file_name(server: &str, tool: &str, n: usize, mime: &str) -> String {+ let clean = |s: &str| -> String {+ let s: String = s.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '-' }).collect();+ s.chars().take(40).collect()+ };+ format!("{}-{}-{n}.{}", clean(server), clean(tool), extension(mime))+}++/// What became of one file, for the model.+fn saved_line(noun: &str, saved: &SavedFile) -> String {+ if saved.already {+ format!("{noun} already in this chat as {} (id {}): the same file was shared a few minutes ago.", saved.name, saved.id)+ } else {+ format!("{noun} saved in this chat as {} (id {}); the person sees it there.", saved.name, saved.id)+ }+}++/// One call's file saving: counts what it saved against [`MAX_FILES_PER_CALL`] and numbers names.+struct Saver<'a> {+ sink: Option<&'a dyn MediaSink>,+ server: &'a str,+ tool: &'a str,+ saved: usize,+ named: usize,+}++impl Saver<'_> {+ fn full(&self) -> bool {+ self.saved >= MAX_FILES_PER_CALL+ }++ async fn save(&mut self, bytes: Vec<u8>, declared: &str) -> Result<SavedFile, String> {+ let Some(sink) = self.sink else {+ return Err("this turn has no chat to save it in".into());+ };+ self.named += 1;+ let mime = real_mime(&bytes, declared);+ let name = file_name(self.server, self.tool, self.named, mime);+ let saved = sink.save(bytes, &name, self.server).await?;+ self.saved += 1;+ Ok(saved)+ }+}++/// The text the model gets for a successful call: [`ToolCallResult::text`], with every file part+/// saved in the chat and named by its saved file, and (for an app with a [`DeliveryRule`]) every+/// delivery link downloaded and replaced by its saved file. `sink` is the turn's chat; without one+/// the model is told a file came back but couldn't be saved.+pub async fn finish(result: &ToolCallResult, server: &str, server_url: Option<&str>, tool: &str, sink: Option<&dyn MediaSink>) -> String {+ let delivery = CreditApp::of_server(server, server_url).and_then(DeliveryRule::for_app);+ finish_with(result, server, tool, sink, delivery.as_ref()).await+}++async fn finish_with(result: &ToolCallResult, server: &str, tool: &str, sink: Option<&dyn MediaSink>, delivery: Option<&DeliveryRule>) -> String {+ let parts: Vec<(usize, FilePart)> = result.raw["content"]+ .as_array()+ .into_iter()+ .flatten()+ .enumerate()+ .filter_map(|(i, item)| file_part(item).map(|p| (i, p)))+ .collect();+ if parts.is_empty() && delivery.is_none() {+ return result.text.clone();+ }+ let mut saver = Saver { sink, server, tool, saved: 0, named: 0 };+ let mut lines: HashMap<usize, String> = HashMap::new();+ for (i, part) in parts {+ let stand_in = format!("[{}: {}]", noun(part.mime).to_lowercase(), part.mime);+ let line = if saver.full() {+ format!("{stand_in} Not saved: only the first {MAX_FILES_PER_CALL} files a tool returns are saved in the chat.")+ } else if part.data.len() / 4 * 3 > MAX_FILE_BYTES {+ format!("{stand_in} {} came back but couldn't be saved: it is larger than 100 MB.", article(noun(part.mime)))+ } else {+ let decoded = base64::engine::general_purpose::STANDARD+ .decode(part.data.trim())+ .map_err(|_| "its data isn't valid base64".to_string());+ match decoded {+ Ok(bytes) => {+ let mime = real_mime(&bytes, part.mime).to_string();+ match saver.save(bytes, &mime).await {+ Ok(saved) => saved_line(noun(&mime), &saved),+ Err(why) => format!("{stand_in} {} came back but couldn't be saved: {why}.", article(noun(&mime))),+ }+ }+ Err(why) => format!("{stand_in} {} came back but couldn't be saved: {why}.", article(noun(part.mime))),+ }+ };+ lines.insert(i, line);+ }+ let mut text = if lines.is_empty() { result.text.clone() } else { result_text_with(&result.raw, |i| lines.get(&i).cloned()) };+ if let Some(rule) = delivery {+ text = save_links(text, rule, &mut saver).await;+ }+ text+}++/// "An image", "An audio file", "A video", "A file".+fn article(noun: &str) -> String {+ let lower = noun.to_lowercase();+ if lower.starts_with(['a', 'e', 'i', 'o', 'u']) {+ format!("An {lower}")+ } else {+ format!("A {lower}")+ }+}++/// The `https://…` and `http://…` links in `text` (each once, in order), ending at whitespace, a+/// quote, a bracket or a backslash, without trailing punctuation. The delivery rule then refuses+/// plain http (only this module's tests allow it).+fn links(text: &str) -> Vec<&str> {+ let mut out: Vec<&str> = Vec::new();+ let mut rest = text;+ while let Some(at) = [rest.find("https://"), rest.find("http://")].into_iter().flatten().min() {+ let tail = &rest[at..];+ let end = tail+ .find(|c: char| c.is_whitespace() || matches!(c, '"' | '\'' | '<' | '>' | '`' | '\\' | ')' | ']' | '}'))+ .unwrap_or(tail.len());+ let link = tail[..end].trim_end_matches(['.', ',', ';', ':']);+ if !out.contains(&link) {+ out.push(link);+ }+ rest = &tail[end.max(7)..];+ }+ out+}++/// Downloads each allowlisted link in `text`, saves it, and puts the saved file in the link's+/// place; a link that can't be saved stays, with the reason added.+async fn save_links(mut text: String, rule: &DeliveryRule, saver: &mut Saver<'_>) -> String {+ let found: Vec<(String, reqwest::Url)> = links(&text)+ .into_iter()+ .filter_map(|l| reqwest::Url::parse(l).ok().filter(|u| rule.allows(u)).map(|u| (l.to_string(), u)))+ .collect();+ let mut notes = Vec::new();+ for (link, url) in found {+ if saver.full() {+ notes.push(format!(+ "Not saved: {link} (only the first {MAX_FILES_PER_CALL} files a tool returns are saved in the chat; the link expires)."+ ));+ continue;+ }+ let outcome = match saver.sink {+ None => Err("this turn has no chat to save it in".to_string()),+ Some(_) => match download(rule, &url).await {+ Ok(bytes) => {+ let mime = real_mime(&bytes, "application/octet-stream").to_string();+ saver.save(bytes, &mime).await.map(|s| (s, mime))+ }+ Err(why) => Err(why),+ },+ };+ match outcome {+ Ok((saved, mime)) => {+ text = text.replace(&link, &format!("kwnt-file:{} ({})", saved.id, saved.name));+ notes.push(saved_line(noun(&mime), &saved));+ }+ Err(why) => notes.push(format!("The file at {link} couldn't be saved in this chat: {why}. The link expires soon.")),+ }+ }+ if !notes.is_empty() {+ if !text.is_empty() {+ text.push('\n');+ }+ text.push_str(¬es.join("\n"));+ }+ text+}++/// 26h D3: claude's PostToolUse hook for an MCP tool call (the claude engine calls the bot's+/// servers itself, so [`finish`] never sees the result). `tool_response` is the content claude+/// made of the result, recorded from claude 2.1.326 (Nov 17):+/// - an `image` part is `{"type":"image","source":{"type":"base64","media_type":…,"data":…}}`,+/// then claude's own `[Image: source: <its local copy>]` text;+/// - an `audio` part (or a blob claude can't show) is only a text line, `[Audio from <server>]+/// Binary content (<type>, <size>) saved to <path>`, with the bytes in claude's `tool-results`+/// folder for this session;+/// - a `resource_link` is `[Resource link: <name>] <uri>`, which the delivery rule reads as a link.+///+/// The parts come back in MCP's shape (`{"content": […]}`) so the same saving runs on them.+/// `tool_results` is that session's `tool-results` folder; a saved-to path is read only when it is+/// a plain file claude wrote there for an MCP tool (`mcp-…-blob-…`), never anywhere a result's+/// text points. Also says whether a part was turned into a note (a file over the cap).+pub fn from_claude(tool_response: &Value, tool_results: Option<&std::path::Path>) -> (Value, bool) {+ let blocks: Vec<Value> = match tool_response {+ Value::Array(a) => a.clone(),+ Value::Object(o) if o.get("content").is_some_and(Value::is_array) => o["content"].as_array().cloned().unwrap_or_default(),+ Value::String(s) => vec![serde_json::json!({"type": "text", "text": s})],+ _ => Vec::new(),+ };+ let mut content = Vec::new();+ let mut noted = false;+ let mut after_image = false;+ for block in blocks {+ let was_image = std::mem::take(&mut after_image);+ let kind = block["type"].as_str().unwrap_or("").to_string();+ match kind.as_str() {+ "image" if block["source"]["type"] == "base64" => {+ if let Some(data) = block["source"]["data"].as_str() {+ let mime = block["source"]["media_type"].as_str().unwrap_or("image/png");+ content.push(serde_json::json!({"type": "image", "mimeType": mime, "data": data}));+ after_image = true;+ continue;+ }+ content.push(block);+ }+ "text" => {+ let text = block["text"].as_str().unwrap_or("");+ // claude's note of where it kept the picture it just showed: the saved line says it now+ if was_image && text.starts_with("[Image: source: ") && text.ends_with(']') && !text.contains('\n') {+ continue;+ }+ match claude_blob(text).map(|(mime, path)| (mime, read_blob(path, tool_results))) {+ Some((mime, Ok(bytes))) => {+ let data = base64::engine::general_purpose::STANDARD.encode(&bytes);+ let part = match mime.split('/').next() {+ Some("image") => serde_json::json!({"type": "image", "mimeType": mime, "data": data}),+ Some("audio") => serde_json::json!({"type": "audio", "mimeType": mime, "data": data}),+ _ => serde_json::json!({"type": "resource", "resource": {"uri": "", "mimeType": mime, "blob": data}}),+ };+ content.push(part);+ }+ Some((mime, Err(BlobError::TooBig))) => {+ noted = true;+ let line = format!(+ "[{}: {mime}] {} came back but couldn't be saved: it is larger than 100 MB.",+ noun(&mime).to_lowercase(),+ article(noun(&mime))+ );+ content.push(serde_json::json!({"type": "text", "text": line}));+ }+ // Not a file claude kept for this session: the text stays as it is+ _ => content.push(block),+ }+ }+ _ => content.push(block),+ }+ }+ (serde_json::json!({ "content": content }), noted)+}++/// The type and path in claude's `[Audio from x] Binary content (audio/wav, 7.9KB) saved to /p`.+fn claude_blob(text: &str) -> Option<(String, &str)> {+ if !["[Audio from ", "[Image from ", "[Resource from "].iter().any(|p| text.starts_with(p)) || text.contains('\n') {+ return None;+ }+ let (_, rest) = text.split_once("] Binary content (")?;+ let (mime, rest) = rest.split_once(", ")?;+ let (_, path) = rest.split_once(") saved to ")?;+ let mime = mime.trim();+ let mime = if mime.contains('/') && !mime.contains(char::is_whitespace) { mime.to_string() } else { "application/octet-stream".to_string() };+ Some((mime, path.trim()))+}++enum BlobError {+ TooBig,+ NotAllowed,+}++/// Reads `path` only when it is a plain file (not a link) directly in `dir`, named the way claude+/// names an MCP tool's blob (`mcp-<server>-blob-…`), and at most [`MAX_FILE_BYTES`].+fn read_blob(path: &str, dir: Option<&std::path::Path>) -> Result<Vec<u8>, BlobError> {+ let dir = dir.and_then(|d| std::fs::canonicalize(d).ok()).ok_or(BlobError::NotAllowed)?;+ let path = std::path::Path::new(path);+ if !path.is_absolute() {+ return Err(BlobError::NotAllowed);+ }+ let meta = std::fs::symlink_metadata(path).map_err(|_| BlobError::NotAllowed)?;+ let real = std::fs::canonicalize(path).map_err(|_| BlobError::NotAllowed)?;+ let name = real.file_name().and_then(|n| n.to_str()).unwrap_or("");+ if !meta.file_type().is_file() || real.parent() != Some(dir.as_path()) || !name.starts_with("mcp-") || !name.contains("-blob-") {+ return Err(BlobError::NotAllowed);+ }+ if meta.len() > MAX_FILE_BYTES as u64 {+ return Err(BlobError::TooBig);+ }+ std::fs::read(&real).map_err(|_| BlobError::NotAllowed)+}++/// 26h D3: [`finish`] for a claude PostToolUse payload's `tool_response` ([`from_claude`]): the+/// files are saved in the chat and the model's text names them. `None` when there is nothing to+/// save (no file part, and no allowlisted delivery link for this app): claude's own output stays.+pub async fn finish_claude(+ tool_response: &Value,+ server: &str,+ server_url: Option<&str>,+ tool: &str,+ sink: Option<&dyn MediaSink>,+ tool_results: Option<&std::path::Path>,+) -> Option<String> {+ let (raw, noted) = from_claude(tool_response, tool_results);+ let delivery = CreditApp::of_server(server, server_url).and_then(DeliveryRule::for_app);+ let text = result_text_with(&raw, |_| None);+ let files = raw["content"].as_array().into_iter().flatten().any(|p| file_part(p).is_some());+ let has_links = delivery+ .as_ref()+ .is_some_and(|rule| links(&text).into_iter().any(|l| reqwest::Url::parse(l).is_ok_and(|u| rule.allows(&u))));+ if !files && !has_links && !noted {+ return None;+ }+ let result = ToolCallResult { text, is_error: false, raw };+ Some(finish_with(&result, server, tool, sink, delivery.as_ref()).await)+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;+ use std::sync::Mutex;++ /// A 1×1 PNG.+ const PNG: &[u8] = &[+ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01,+ 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x44, 0x41,+ 0x54, 0x78, 0x9C, 0x63, 0xF8, 0xCF, 0xC0, 0xF0, 0x1F, 0x00, 0x05, 0x00, 0x01, 0xFF, 0x89, 0x99, 0x3D, 0x1D, 0x00, 0x00,+ 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,+ ];++ fn b64(bytes: &[u8]) -> String {+ base64::engine::general_purpose::STANDARD.encode(bytes)+ }++ /// Keeps what it was given; refuses files over `max` bytes the way the store does.+ #[derive(Default)]+ struct Sink {+ files: Mutex<Vec<(String, Vec<u8>)>>,+ max: Option<usize>,+ }++ #[async_trait]+ impl MediaSink for Sink {+ async fn save(&self, bytes: Vec<u8>, name: &str, _server: &str) -> Result<SavedFile, String> {+ if self.max.is_some_and(|m| bytes.len() > m) {+ return Err("the image is larger than 20 MB".into());+ }+ let mut files = self.files.lock().unwrap();+ let already = files.iter().any(|(_, b)| *b == bytes);+ files.push((name.to_string(), bytes));+ Ok(SavedFile { id: format!("att{}", files.len()), name: name.to_string(), already })+ }+ }++ fn result(content: Value) -> ToolCallResult {+ let raw = json!({ "content": content });+ ToolCallResult { text: result_text_with(&raw, |_| None), is_error: false, raw }+ }++ async fn run(r: &ToolCallResult, sink: Option<&Sink>) -> String {+ finish_with(r, "flux", "generate_image", sink.map(|s| s as &dyn MediaSink), None).await+ }++ #[tokio::test]+ async fn a_png_part_is_saved_and_named_never_sent_as_base64() {+ let sink = Sink::default();+ let r = result(json!([{"type": "image", "mimeType": "image/png", "data": b64(PNG)}]));+ assert_eq!(r.text, "[image: image/png]", "the old stand-in");+ let text = run(&r, Some(&sink)).await;+ assert_eq!(text, "Image saved in this chat as flux-generate_image-1.png (id att1); the person sees it there.");+ assert!(!text.contains(&b64(PNG)[..12]));+ let files = sink.files.lock().unwrap();+ assert_eq!(files.len(), 1);+ assert_eq!(files[0].1, PNG);+ }++ #[tokio::test]+ async fn bad_base64_keeps_the_stand_in_with_the_reason() {+ let sink = Sink::default();+ let r = result(json!([{"type": "image", "mimeType": "image/png", "data": "not base64!!"}]));+ let text = run(&r, Some(&sink)).await;+ assert_eq!(text, "[image: image/png] An image came back but couldn't be saved: its data isn't valid base64.");+ assert!(sink.files.lock().unwrap().is_empty());+ }++ #[tokio::test]+ async fn text_and_pictures_keep_their_order() {+ let sink = Sink::default();+ let r = result(json!([+ {"type": "text", "text": "Here you go"},+ {"type": "image", "mimeType": "image/png", "data": b64(PNG)},+ {"type": "text", "text": "seed 42"},+ {"type": "resource", "resource": {"uri": "file:///x.png", "mimeType": "image/png", "blob": b64(PNG)}},+ {"type": "resource", "resource": {"uri": "file:///notes.txt", "text": "a note"}},+ ]));+ let text = run(&r, Some(&sink)).await;+ let lines: Vec<&str> = text.lines().collect();+ assert_eq!(lines[0], "Here you go");+ assert!(lines[1].starts_with("Image saved in this chat as flux-generate_image-1.png (id att1)"), "{text}");+ assert_eq!(lines[2], "seed 42");+ assert!(lines[3].starts_with("Image already in this chat as flux-generate_image-2.png (id att2)"), "same bytes: {text}");+ assert_eq!(lines[4], "a note", "a text resource stays text");+ }++ #[tokio::test]+ async fn an_oversized_part_is_skipped_and_the_others_still_save() {+ let sink = Sink { max: Some(1000), ..Default::default() };+ let mut big = PNG.to_vec();+ big.resize(5000, 0);+ let r = result(json!([+ {"type": "image", "mimeType": "image/png", "data": b64(&big)},+ {"type": "image", "mimeType": "image/png", "data": b64(PNG)},+ ]));+ let text = run(&r, Some(&sink)).await;+ let lines: Vec<&str> = text.lines().collect();+ assert_eq!(lines[0], "[image: image/png] An image came back but couldn't be saved: the image is larger than 20 MB.");+ assert!(lines[1].starts_with("Image saved in this chat as flux-generate_image-2.png"), "{text}");+ assert_eq!(sink.files.lock().unwrap().len(), 1);+ }++ #[tokio::test]+ async fn a_part_over_100_mb_is_never_decoded() {+ let sink = Sink::default();+ // Only its length is read: 140 M base64 characters stand for 105 MB+ let huge = "A".repeat(140 * 1024 * 1024);+ let r = result(json!([{"type": "audio", "mimeType": "audio/wav", "data": huge}]));+ let text = run(&r, Some(&sink)).await;+ assert_eq!(text, "[audio file: audio/wav] An audio file came back but couldn't be saved: it is larger than 100 MB.");+ }++ #[tokio::test]+ async fn only_the_first_ten_files_are_saved() {+ let sink = Sink::default();+ let parts: Vec<Value> = (0..12u8)+ .map(|n| {+ let mut png = PNG.to_vec();+ png.push(n); // distinct bytes, so none is a repeat+ json!({"type": "image", "mimeType": "image/png", "data": b64(&png)})+ })+ .collect();+ let text = run(&result(json!(parts)), Some(&sink)).await;+ let lines: Vec<&str> = text.lines().collect();+ assert_eq!(lines.len(), 12);+ assert!(lines[9].starts_with("Image saved in this chat as flux-generate_image-10.png"), "{text}");+ assert_eq!(lines[10], "[image: image/png] Not saved: only the first 10 files a tool returns are saved in the chat.");+ assert_eq!(lines[11], lines[10]);+ assert_eq!(sink.files.lock().unwrap().len(), 10);+ }++ #[tokio::test]+ async fn without_a_chat_the_model_is_told_it_wasnt_saved() {+ let r = result(json!([{"type": "image", "mimeType": "image/png", "data": b64(PNG)}]));+ let text = run(&r, None).await;+ assert_eq!(text, "[image: image/png] An image came back but couldn't be saved: this turn has no chat to save it in.");+ }++ #[tokio::test]+ async fn the_real_type_names_the_file() {+ let sink = Sink::default();+ // Declared as JPEG, but the bytes are a PNG+ let r = result(json!([{"type": "image", "mimeType": "image/jpeg", "data": b64(PNG)}]));+ let text = run(&r, Some(&sink)).await;+ assert!(text.starts_with("Image saved in this chat as flux-generate_image-1.png"), "{text}");+ }++ #[tokio::test]+ async fn text_only_results_are_untouched() {+ let r = result(json!([{"type": "text", "text": "https://delivery-eu1.bfl.ai/x.png"}]));+ assert_eq!(run(&r, Some(&Sink::default())).await, r.text, "no delivery rule for this server");+ }++ #[test]+ fn delivery_hosts_are_allowlisted() {+ let rule = DeliveryRule::for_app(CreditApp::Bfl).unwrap();+ let ok = |u: &str| rule.allows(&reqwest::Url::parse(u).unwrap());+ assert!(ok("https://delivery-eu1.bfl.ai/results/ab/cd/sample.jpeg?se=2026&sig=x"));+ assert!(ok("https://delivery-us1.bfl.ai/results/x.png"));+ assert!(ok("https://delivery.eu.bfl.ai/x.png"));+ assert!(!ok("http://delivery-eu1.bfl.ai/x.png"), "https only");+ assert!(!ok("https://delivery-eu1.bfl.ai:8443/x.png"), "the default port only");+ assert!(!ok("https://user:[email protected]/x.png"));+ assert!(!ok("https://api.bfl.ai/x.png"), "not a delivery host");+ assert!(!ok("https://mcp.bfl.ai/x.png"));+ assert!(!ok("https://delivery-eu1.bfl.ai.evil.com/x.png"));+ assert!(!ok("https://deliverybfl.ai/x.png"));+ assert!(!ok("https://.bfl.ai/x.png"));+ assert!(!ok("https://169.254.169.254/latest/meta-data"));+ assert!(!ok("https://127.0.0.1/x.png"));+ assert!(DeliveryRule::for_app(CreditApp::Picsart).is_none(), "Picsart's CDN isn't on any list yet");+ }++ #[test]+ fn links_are_found_whole_and_once() {+ let text = r#"{"image_url": "https://delivery-eu1.bfl.ai/r/a.jpeg?se=1&sig=a%2Fb", "again": "https://delivery-eu1.bfl.ai/r/a.jpeg?se=1&sig=a%2Fb"} see (https://x.example/p). https://y.example/q, end"#;+ assert_eq!(+ links(text),+ ["https://delivery-eu1.bfl.ai/r/a.jpeg?se=1&sig=a%2Fb", "https://x.example/p", "https://y.example/q"]+ );+ assert_eq!(links("a http://127.0.0.1:9/png, b"), ["http://127.0.0.1:9/png"]);+ }++ /// A local file host: `/png` is a picture, `/away` redirects off the list, `/hop` redirects+ /// to `/png`, `/missing` is a 404. [`big_host`] claims 200 MB.+ async fn file_host() -> String {+ use axum::{routing::get, Router};+ let app = Router::new()+ .route("/png", get(|| async { ([("content-type", "image/png")], PNG.to_vec()) }))+ .route("/hop", get(|| async { axum::response::Redirect::temporary("/png") }))+ .route("/away", get(|| async { axum::response::Redirect::temporary("http://localhost:1/png") }))+ .route("/missing", get(|| async { axum::http::StatusCode::NOT_FOUND }));+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ tokio::spawn(async move { axum::serve(listener, app).await.ok() });+ format!("http://{addr}")+ }++ /// A raw host whose every answer declares 200 MB but sends one byte. hyper refuses to serve a+ /// body shorter than its own content-length header (a debug-build panic that drops the+ /// connection), so this one writes the response by hand.+ async fn big_host() -> String {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ tokio::spawn(async move {+ while let Ok((mut socket, _)) = listener.accept().await {+ tokio::spawn(async move {+ let mut request = [0u8; 4096];+ let _ = socket.read(&mut request).await;+ let head = format!("HTTP/1.1 200 OK\r\ncontent-type: image/png\r\ncontent-length: {}\r\n\r\nx", 200 * 1024 * 1024);+ let _ = socket.write_all(head.as_bytes()).await;+ // Held open: the client must refuse on the header, not on a short body+ tokio::time::sleep(std::time::Duration::from_secs(5)).await;+ });+ }+ });+ format!("http://{addr}/big")+ }++ fn local_rule() -> DeliveryRule {+ DeliveryRule { hosts: vec![HostPattern { suffix: "127.0.0.1", label_prefix: "" }], https_only: false, public_only: false }+ }++ #[tokio::test]+ async fn a_delivery_link_is_downloaded_saved_and_replaced() {+ let base = file_host().await;+ let sink = Sink::default();+ let link = format!("{base}/png");+ let r = result(json!([{"type": "text", "text": format!("{{\"image_url\": \"{link}\", \"seed\": 7}}")}]));+ let text = finish_with(&r, "flux", "generate_image", Some(&sink), Some(&local_rule())).await;+ assert!(!text.contains(&link), "{text}");+ assert!(text.starts_with("{\"image_url\": \"kwnt-file:att1 (flux-generate_image-1.png)\", \"seed\": 7}"), "{text}");+ assert!(text.ends_with("\nImage saved in this chat as flux-generate_image-1.png (id att1); the person sees it there."), "{text}");+ assert_eq!(sink.files.lock().unwrap()[0].1, PNG);+ // A redirect within the list is followed+ let r = result(json!([{"type": "text", "text": format!("{base}/hop")}]));+ let text = finish_with(&r, "flux", "generate_image", Some(&sink), Some(&local_rule())).await;+ assert!(text.contains("Image already in this chat"), "{text}");+ }++ #[tokio::test]+ async fn a_delivery_link_that_cant_be_saved_stays_with_the_reason() {+ let base = file_host().await;+ let sink = Sink::default();+ for (link, why) in [+ (format!("{base}/away"), "it redirects off the app's file hosts"),+ (big_host().await, "it is larger than 100 MB"),+ (format!("{base}/missing"), "the file host answered 404"),+ ] {+ let r = result(json!([{"type": "text", "text": format!("image: {link}")}]));+ let text = finish_with(&r, "flux", "generate_image", Some(&sink), Some(&local_rule())).await;+ assert_eq!(text, format!("image: {link}\nThe file at {link} couldn't be saved in this chat: {why}. The link expires soon."));+ }+ // Links off the list are left alone and never fetched+ let r = result(json!([{"type": "text", "text": "see https://example.com/a.png"}]));+ let text = finish_with(&r, "flux", "generate_image", Some(&sink), Some(&local_rule())).await;+ assert_eq!(text, "see https://example.com/a.png");+ assert!(sink.files.lock().unwrap().is_empty());+ }++ #[tokio::test]+ async fn the_real_rule_refuses_a_local_address_before_connecting() {+ let rule = DeliveryRule::for_app(CreditApp::Bfl).unwrap();+ let url = reqwest::Url::parse("https://127.0.0.1/x.png").unwrap();+ assert_eq!(download(&rule, &url).await, Err("its address isn't one of the app's file hosts".into()));+ }++ /// claude's PostToolUse `tool_response` for an image, as claude 2.1.326 sent it (Nov 17).+ fn claude_image(local_copy: &str) -> Value {+ json!([+ {"type": "text", "text": "Here is your picture."},+ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": b64(PNG)}},+ {"type": "text", "text": format!("[Image: source: {local_copy}]")}+ ])+ }++ async fn claude(resp: &Value, sink: Option<&Sink>, dir: Option<&std::path::Path>) -> Option<String> {+ finish_claude(resp, "flux", None, "generate_image", sink.map(|s| s as &dyn MediaSink), dir).await+ }++ #[tokio::test]+ async fn a_claude_hook_picture_is_saved_and_claudes_local_copy_line_goes() {+ let sink = Sink::default();+ let text = claude(&claude_image("/h/.claude/projects/-w/s1/tool-results/mcp-flux-blob-1.png"), Some(&sink), None).await.unwrap();+ assert_eq!(+ text,+ "Here is your picture.\nImage saved in this chat as flux-generate_image-1.png (id att1); the person sees it there."+ );+ assert!(!text.contains("tool-results") && !text.contains(&b64(PNG)[..12]), "{text}");+ assert_eq!(sink.files.lock().unwrap()[0].1, PNG);+ // Without a chat the model still hears why+ let none = claude(&claude_image("/x"), None, None).await.unwrap();+ assert!(none.contains("[image: image/png] An image came back but couldn't be saved: this turn has no chat to save it in."), "{none}");+ // Text only, or a link no rule allows: nothing to do, claude's own output stays+ assert_eq!(claude(&json!([{"type": "text", "text": "done"}]), Some(&sink), None).await, None);+ assert_eq!(claude(&json!("done"), Some(&sink), None).await, None);+ let link = json!([{"type": "text", "text": "[Resource link: y.png] https://example.com/y.png"}]);+ assert_eq!(claude(&link, Some(&sink), None).await, None);+ // A text that only looks like claude's copy line, not after a picture, stays+ let (raw, _) = from_claude(&json!([{"type": "text", "text": "[Image: source: /etc/x]"}]), None);+ assert_eq!(raw["content"][0]["text"], "[Image: source: /etc/x]");+ }++ #[tokio::test]+ async fn a_claude_hook_audio_file_is_read_only_from_the_sessions_tool_results() {+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path().join("s1").join("tool-results");+ std::fs::create_dir_all(&dir).unwrap();+ let wav = b"RIFF\x24\x00\x00\x00WAVEfmt more".to_vec();+ let kept = dir.join("mcp-flux-blob-1794927836623-qzwmn2.wav");+ std::fs::write(&kept, &wav).unwrap();+ fn line(p: &std::path::Path) -> Value {+ json!([{"type": "text", "text": format!("[Audio from flux] Binary content (audio/wav, 7.9KB) saved to {}", p.display())}])+ }+ let sink = Sink::default();+ let text = claude(&line(&kept), Some(&sink), Some(&dir)).await.unwrap();+ assert_eq!(text, "Audio file saved in this chat as flux-generate_image-1.wav (id att1); the person sees it there.");+ assert_eq!(sink.files.lock().unwrap()[0].1, wav);++ // A path elsewhere, a file claude didn't name as a tool's blob, or no folder: not read+ let outside = tmp.path().join("mcp-flux-blob-2.wav");+ std::fs::write(&outside, &wav).unwrap();+ let other = dir.join("toolu_01.txt");+ std::fs::write(&other, b"secret").unwrap();+ let sink = Sink::default();+ for (path, folder) in [(&outside, Some(dir.as_path())), (&other, Some(dir.as_path())), (&kept, None)] {+ assert_eq!(claude(&line(path), Some(&sink), folder).await, None, "{}", path.display());+ }+ let walk = dir.join("..").join("..").join("mcp-flux-blob-2.wav");+ assert_eq!(claude(&line(&walk), Some(&sink), Some(&dir)).await, None, "a .. path out of the folder");+ assert!(sink.files.lock().unwrap().is_empty());+ #[cfg(unix)]+ {+ let link = dir.join("mcp-flux-blob-3.wav");+ std::os::unix::fs::symlink(outside.as_path(), &link).unwrap();+ assert_eq!(claude(&line(&link), Some(&sink), Some(&dir)).await, None, "a link in the folder isn't followed");+ // Over the cap: named, not read+ let big = dir.join("mcp-flux-blob-4.mp4");+ std::fs::File::create(&big).unwrap().set_len(MAX_FILE_BYTES as u64 + 1).unwrap();+ let msg = json!([{"type": "text", "text": format!("[Resource from flux at file:///v.mp4] Binary content (video/mp4, 100MB) saved to {}", big.display())}]);+ let text = claude(&msg, Some(&sink), Some(&dir)).await.unwrap();+ assert_eq!(text, "[video: video/mp4] A video came back but couldn't be saved: it is larger than 100 MB.");+ assert!(sink.files.lock().unwrap().is_empty());+ }+ }+}diff --git a/src/mcp/mod.rs b/src/mcp/mod.rsindex 5ca2ee1b..ea63cd4a 100644--- a/src/mcp/mod.rs+++ b/src/mcp/mod.rs@@ -10,6 +10,7 @@ pub mod declined;pub mod echo_server;pub mod fetch_risk;pub mod home_floor;+pub mod media;pub mod oauth;pub mod payment_floor;pub mod prod_floor;@@ -596,6 +597,10 @@ pub struct McpTurnContext {/// CLIs run with none of their built-in tools, so their own allow rules have nothing to let/// through without a card. A CLI that can't be held to that runs the turn with no tools.pub kwnt_only: bool,+ /// 26h: where pictures, audio and video an MCP tool returns are saved and shown in the+ /// turn's chat ([`media::MediaSink`]). `None` (no chat to post into): the model is told a+ /// file came back but couldn't be saved.+ pub media: Option<Arc<dyn media::MediaSink>>,}/// Where an agent CLI reaches this turn's MCP gateway. The token is sent as a bearer token.@@ -654,6 +659,7 @@ impl std::fmt::Debug for McpTurnContext {.field("permission_url", &self.permission_url.as_ref().map(|_| "<set>")).field("gateway", &self.gateway).field("max_tool_iterations", &self.max_tool_iterations)+ .field("media", &self.media.as_ref().map(|_| "<set>")).finish()}}diff --git a/src/mcp/payment_floor.rs b/src/mcp/payment_floor.rsindex bb647974..09ca5553 100644--- a/src/mcp/payment_floor.rs+++ b/src/mcp/payment_floor.rs@@ -291,6 +291,11 @@ pub fn page_reason(action: &str, key: Option<&str>, page: &PageSignals) -> Optio/// An MCP tool (incl. Composio): by its name and server, the Composio slugs it runs, and for/// browser-type tools, the label it clicks or the card number it types.fn mcp_reason(server: &str, tool: &str, args: &Value) -> Option<String> {+ // 26h: a generation on an app that bills the person's own credits (by its server name here;+ // [`credits_reason`] with the server's address also knows a renamed one)+ if let Some(why) = credits_reason(server, None, tool) {+ return Some(why);+ }let mut names = vec![tool.to_string()];collect_slugs(args, &mut names, 0);for name in &names {@@ -330,6 +335,119 @@ fn mcp_reason(server: &str, tool: &str, args: &Value) -> Option<String> {None}+/// 26h: an MCP app whose tools spend the person's own credits there (a picture or a video made+/// with their account). kwnt never resells credits and never knows a price: the card only says+/// whose credits a call uses.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum CreditApp {+ /// Black Forest Labs' FLUX server (`https://mcp.bfl.ai`).+ Bfl,+ /// Picsart's GenAI server (`https://api.picsart.com/gen-ai/mcp`).+ Picsart,+}++impl CreditApp {+ pub const ALL: [CreditApp; 2] = [CreditApp::Bfl, CreditApp::Picsart];++ /// The name the card uses: "uses your <label> credits".+ pub fn label(self) -> &'static str {+ match self {+ CreditApp::Bfl => "Black Forest Labs",+ CreditApp::Picsart => "Picsart",+ }+ }++ /// Server names that are this app, compared without case, `-`, `_`, spaces or a trailing+ /// number (`flux`, `FLUX`, `black-forest-labs`, `picsart-2`).+ fn names(self) -> &'static [&'static str] {+ match self {+ CreditApp::Bfl => &["flux", "bfl", "blackforestlabs"],+ CreditApp::Picsart => &["picsart"],+ }+ }++ /// Hosts that are this app's server: the domain itself or any name under it.+ fn domains(self) -> &'static [&'static str] {+ match self {+ CreditApp::Bfl => &["bfl.ai"],+ CreditApp::Picsart => &["picsart.com"],+ }+ }++ /// Tools that make something with the person's credits (checked against the servers' own+ /// tool lists, Nov 17 2026: BFL's README and Picsart's listing, whose generate, edit, upscale+ /// and render tools say they spend credits).+ fn spends(self) -> &'static [&'static str] {+ match self {+ CreditApp::Bfl => &[+ "generate_image", "generate_variations", "vto", "generate_video", "enhance_video", "upscale_video", "edit_video",+ ],+ CreditApp::Picsart => &[+ "picsart_generate", "picsart_remove_bg", "picsart_change_bg", "picsart_enhance", "picsart_vectorize",+ "picsart_media_contact_sheet", "picsart_media_export",+ ],+ }+ }++ /// Tools that only read (a balance, a job's status, a catalog, a guide, an upload address).+ fn reads(self) -> &'static [&'static str] {+ match self {+ CreditApp::Bfl => &["get_credits", "get_history", "get_result", "list_skills", "get_skill", "request_upload_url"],+ CreditApp::Picsart => &[+ "picsart_credits", "picsart_job_status", "picsart_list_models", "picsart_model_catalog", "picsart_model_params",+ "picsart_preflight",+ ],+ }+ }++ /// Whether a tool this list doesn't name spends credits unless its name only reads. BFL's+ /// server is all generation apart from its reads, so a new tool there asks; Picsart's also+ /// edits scenes locally and keeps a drive, which cost nothing, so only its listed tools ask.+ fn unlisted_spend(self) -> bool {+ matches!(self, CreditApp::Bfl)+ }++ /// Which credit app the MCP server `name` (at `url`, when known) is.+ pub fn of_server(name: &str, url: Option<&str>) -> Option<CreditApp> {+ let plain: String = name.chars().filter(|c| c.is_alphanumeric()).collect::<String>().to_lowercase();+ let plain = plain.trim_end_matches(|c: char| c.is_ascii_digit());+ let host = url+ .and_then(|u| url::Url::parse(u).ok())+ .and_then(|u| u.host_str().map(|h| h.trim_end_matches('.').to_ascii_lowercase()));+ Self::ALL.into_iter().find(|app| {+ app.names().contains(&plain)+ || host.as_deref().is_some_and(|h| app.domains().iter().any(|d| h == *d || h.ends_with(&format!(".{d}"))))+ })+ }++ /// Whether `tool` on this app uses the person's credits.+ pub fn spends_on(self, tool: &str) -> bool {+ let tool = tool.to_ascii_lowercase();+ if self.reads().contains(&tool.as_str()) {+ return false;+ }+ self.spends().contains(&tool.as_str()) || (self.unlisted_spend() && !reads_only(&words(&tool)))+ }++ /// The payment reason a credit call carries; [`CreditApp::of_reason`] reads it back.+ fn reason(self, tool: &str) -> String {+ format!("{tool} uses your {} credits", self.label())+ }++ /// The credit app a payment reason names, for the card's "Uses your … credits" heading.+ pub fn of_reason(why: &str) -> Option<CreditApp> {+ Self::ALL.into_iter().find(|app| why.ends_with(&format!(" uses your {} credits", app.label())))+ }+}++/// Why a call to `tool` on the MCP server `server` (at `url`, when known) asks as a payment: it+/// spends the person's credits on a credit app ([`CreditApp`]). Matched on the server's name or+/// its address, never on the tool alone: a shop's `generate_image` isn't a payment.+pub fn credits_reason(server: &str, url: Option<&str>, tool: &str) -> Option<String> {+ let app = CreditApp::of_server(server, url)?;+ app.spends_on(tool).then(|| app.reason(tool))+}+/// A tool or slug name that pays: any write tool of a money-only app, or a money verb with a/// money noun. A name whose first action word only reads never pays.pub fn name_reason(server: &str, name: &str) -> Option<String> {@@ -813,6 +931,60 @@ mod tests {assert!(mcp("shop", "get_order", json!({})).is_none());}+ /// 26h: a generation that spends the person's FLUX or Picsart credits always asks; the+ /// apps' reads don't, and the same tool name on another server isn't a payment.+ #[test]+ fn credit_generations_ask_and_reads_dont() {+ let flux = mcp("flux", "generate_image", json!({"prompt": "a cat"}));+ assert_eq!(flux.as_deref(), Some("generate_image uses your Black Forest Labs credits"));+ for tool in ["generate_variations", "vto", "generate_video", "enhance_video", "upscale_video", "edit_video"] {+ assert!(mcp("flux", tool, json!({})).is_some(), "flux {tool} asks");+ }+ for tool in ["get_credits", "get_history", "get_result", "list_skills", "get_skill", "request_upload_url"] {+ assert_eq!(mcp("flux", tool, json!({})), None, "flux {tool} only reads");+ }+ // BFL's server is all generation: a tool it adds later asks unless its name only reads+ assert!(mcp("flux", "inpaint_image", json!({})).is_some());+ assert_eq!(mcp("flux", "list_models", json!({})), None);+ // Other names it goes by+ for server in ["bfl", "FLUX", "black-forest-labs", "Black Forest Labs", "flux-2"] {+ assert!(mcp(server, "generate_image", json!({})).is_some(), "{server}");+ }+ assert_eq!(+ mcp("picsart", "picsart_generate", json!({"model": "flux-dev"})).as_deref(),+ Some("picsart_generate uses your Picsart credits")+ );+ for tool in ["picsart_remove_bg", "picsart_change_bg", "picsart_enhance", "picsart_vectorize", "picsart_media_contact_sheet"] {+ assert!(mcp("picsart", tool, json!({})).is_some(), "picsart {tool} asks");+ }+ for tool in ["picsart_credits", "picsart_job_status", "picsart_list_models", "picsart_preflight", "picsart_drive", "picsart_media_patch_scene"] {+ assert_eq!(mcp("picsart", tool, json!({})), None, "picsart {tool} spends nothing");+ }+ // Not a credit app: the old rules, unchanged+ assert_eq!(mcp("shop", "generate_image", json!({})), None, "a shop's generate_image isn't a payment");+ assert_eq!(mcp("comfyui", "generate_image", json!({})), None);+ assert!(mcp("stripe", "create_charge", json!({})).is_some(), "stripe still asks");+ assert_eq!(mcp("github", "create_issue", json!({})), None, "github still doesn't");+ }++ /// A renamed server is still known by its address; a lookalike host isn't.+ #[test]+ fn credit_apps_are_known_by_address() {+ let at = |url: &str| credits_reason("images", Some(url), "generate_image");+ assert!(at("https://mcp.bfl.ai").is_some());+ assert!(at("https://mcp.bfl.ai/mcp").is_some());+ assert!(at("https://eu.mcp.bfl.ai/").is_some());+ assert_eq!(at("https://bfl.ai.example.com/mcp"), None, "only the domain itself or names under it");+ assert_eq!(at("https://notbfl.ai/mcp"), None);+ assert_eq!(at("not a url"), None);+ assert!(credits_reason("design", Some("https://api.picsart.com/gen-ai/mcp"), "picsart_generate").is_some());+ assert_eq!(credits_reason("design", Some("https://api.picsart.com/gen-ai/mcp"), "picsart_credits"), None);+ assert_eq!(credits_reason("images", None, "generate_image"), None);+ assert_eq!(CreditApp::of_reason("generate_image uses your Black Forest Labs credits"), Some(CreditApp::Bfl));+ assert_eq!(CreditApp::of_reason("picsart_generate uses your Picsart credits"), Some(CreditApp::Picsart));+ assert_eq!(CreditApp::of_reason("stripe create_charge looks like a payment"), None);+ }+#[test]fn composio_slugs_are_read_from_the_arguments() {let multi = |slug: &str| json!({"tools": [{"tool_slug": "GMAIL_FETCH_EMAILS", "arguments": {}}, {"tool_slug": slug, "arguments": {"amount": 100}}]});diff --git a/src/mcp/session.rs b/src/mcp/session.rsindex 6ec8e310..94072d75 100644--- a/src/mcp/session.rs+++ b/src/mcp/session.rs@@ -286,6 +286,7 @@ impl McpToolSession {Some(_) if !arguments.is_object() => ("error", "Tool arguments must be a JSON object.".to_string()),Some(t) => {let (server, client) = &self.clients[t.server_index];+ let server_url = self.ctx.servers.iter().find(|s| &s.name == server).and_then(|s| s.url.as_deref());let req = ToolApprovalRequest {kwant_id: caller.kwant_id.clone(),kwant_name: caller.kwant_name.clone(),@@ -296,7 +297,8 @@ impl McpToolSession {arguments: arguments.clone(),builtin: None,smart: Some(read_only_verdict(t.tool.read_only)),- payment: None,+ // 26h: a paid generation (FLUX, Picsart credits) always asks, also by its address+ payment: super::payment_floor::credits_reason(server, server_url, &t.tool.name),};// B2: a write to a GitHub branch waits for its pre-push card before any card or rulematch self.ctx.approver.prepush_gate(&req).await {@@ -314,7 +316,8 @@ impl McpToolSession {} else {match client.call_tool(&t.tool.name, arguments.clone()).await {Ok(r) if r.is_error => ("error", r.text),- Ok(r) => ("ok", r.text),+ // 26h: files it returned are saved in the chat and named, never sent as base64+ Ok(r) => ("ok", super::media::finish(&r, server, server_url, &t.tool.name, self.ctx.media.as_deref()).await),Err(e) => ("error", format!("Tool call failed: {e}")),}}diff --git a/src/sandbox/agent_vm/mod.rs b/src/sandbox/agent_vm/mod.rsindex 0d1d2a13..c1a245ae 100644--- a/src/sandbox/agent_vm/mod.rs+++ b/src/sandbox/agent_vm/mod.rs@@ -1748,6 +1748,7 @@ mod tests {approvals: crate::mcp::Approvals::Ask,records: Default::default(),kwnt_only: false,+ media: None,};let (path, mut dropped) = turn.write_mcp_config(&ctx).unwrap();dropped.sort();diff --git a/src/server/attachments.rs b/src/server/attachments.rsindex f8a2a417..ed0e474f 100644--- a/src/server/attachments.rs+++ b/src/server/attachments.rs@@ -1078,7 +1078,7 @@ pub async fn tool_share(state: &AppState, scope: &SelfScope, args: &Value) -> (S}Err(StoreError::Io) => return ("Could not read or store the file.".into(), true),};- match post_file(state, scope, stored, &name, false).await {+ match post_file(state, scope, stored, &name, false, None).await {Ok(Posted::New(a)) => (format!("Shared {name} with the user as a download (id {}).", a.id), false),Ok(Posted::Already(a)) => (format!("{name} is already in this chat (id {}): you shared these exact bytes a few minutes ago, so it wasn't posted again.", a.id),@@ -1115,9 +1115,17 @@ pub fn is_file_share(m: &crate::db::models::Message) -> bool {/// The message is `{sender_role: "kwant", sender_id: <bot name>, text: "Shared a file: <name>"}`,/// the way a reply names its bot, with meta/// `{"kind": "file", "attachments": [card], "kwant_id", "kwant_name", "turn_id", "auto"}`-/// (`auto`: the reply guard shared it, the bot didn't ask). An image marks the turn as having-/// shared one, also when it was already there.-pub async fn post_file(state: &AppState, scope: &SelfScope, stored: Stored, name: &str, auto: bool) -> Result<Posted, String> {+/// (`auto`: the reply guard shared it, the bot didn't ask), plus `"made_with": <MCP server name>`+/// when an MCP tool made the file ([`ChatMedia`]). An image marks the turn as having shared one,+/// also when it was already there.+pub async fn post_file(+ state: &AppState,+ scope: &SelfScope,+ stored: Stored,+ name: &str,+ auto: bool,+ made_with: Option<&str>,+) -> Result<Posted, String> {let Some(origin) = &scope.origin else {return Err("This turn has no chat to share into.".into());};@@ -1166,7 +1174,7 @@ pub async fn post_file(state: &AppState, scope: &SelfScope, stored: Stored, nametool_calls: None,tokens_used: 0,};- let meta = json!({+ let mut meta = json!({"kind": "file","attachments": cards(std::slice::from_ref(&a)),"kwant_id": scope.kwant_id,@@ -1174,6 +1182,9 @@ pub async fn post_file(state: &AppState, scope: &SelfScope, stored: Stored, name"turn_id": scope.turn_id,"auto": auto,});+ if let Some(server) = made_with.map(str::trim).filter(|s| !s.is_empty()) {+ meta["made_with"] = json!(server);+ }let extra = MessageExtra { thread_id: origin.thread_id.clone(), meta: Some(meta) };let Ok(saved) = state.db.insert_message_with(&msg, &extra).await else {return Err("Could not post the file in the chat.".into());@@ -1198,6 +1209,37 @@ pub async fn post_file(state: &AppState, scope: &SelfScope, stored: Stored, nameOk(Posted::New(a))}+/// 26h: where the files an MCP tool returns go ([`crate::mcp::media`]): stored like a share and+/// posted in the turn's chat as the bot's file (`auto`: kwnt shared it, the bot didn't ask;+/// `made_with`: the MCP server's name), with [`post_file`]'s sha256 dedupe.+pub struct ChatMedia {+ pub state: AppState,+ pub scope: SelfScope,+}++#[async_trait::async_trait]+impl crate::mcp::media::MediaSink for ChatMedia {+ async fn save(&self, bytes: Vec<u8>, name: &str, server: &str) -> Result<crate::mcp::media::SavedFile, String> {+ let name = clean_name(name);+ let stored = store_bytes(&root(&self.state), &bytes, &name).await.map_err(|e| match e {+ StoreError::TooLarge(Cap::Video) => "the video is larger than 100 MB".to_string(),+ StoreError::TooLarge(Cap::Audio) => "the audio file is larger than 100 MB".to_string(),+ StoreError::TooLarge(_) => "the file is larger than 20 MB (videos and audio up to 100 MB)".to_string(),+ StoreError::Empty => "the file is empty".to_string(),+ StoreError::Unsupported => {+ "only images, videos (MP4, MOV, WebM), audio (MP3, M4A, AAC, WAV, OGG, Opus, FLAC), PDFs and UTF-8 text files can be shared".to_string()+ }+ StoreError::Io => "it could not be stored".to_string(),+ })?;+ let saved = |a: Attachment, already| crate::mcp::media::SavedFile { id: a.id, name: a.name, already };+ match post_file(&self.state, &self.scope, stored, &name, true, Some(server)).await {+ Ok(Posted::New(a)) => Ok(saved(a, false)),+ Ok(Posted::Already(a)) => Ok(saved(a, true)),+ Err(why) => Err(lowercase_first(why.trim_end_matches('.'))),+ }+ }+}+/// Stores a JPEG screenshot (base64, as the browser returned it) and posts it as the bot (see/// [`post_file`]). `name` is cleaned like any shared file's.pub async fn post_screenshot(state: &AppState, scope: &SelfScope, data_b64: &str, name: &str, auto: bool) -> Result<Posted, String> {@@ -1213,7 +1255,7 @@ pub async fn post_screenshot(state: &AppState, scope: &SelfScope, data_b64: &strErr(StoreError::Empty) => return Err("The screenshot is empty.".into()),Err(StoreError::Io) => return Err("Could not store the screenshot.".into()),};- post_file(state, scope, stored, &name, auto).await+ post_file(state, scope, stored, &name, auto, None).await}/// `p` (relative to the workspace, or absolute) opened, with its resolved path for the name;@@ -1232,6 +1274,12 @@ pub fn inside_workspace(workspace: &FsPath, p: &str) -> Option<(std::fs::File, PSome((file, real))}+/// "This turn has …" as "this turn has …", for a reason inside a sentence.+fn lowercase_first(s: &str) -> String {+ let mut c = s.chars();+ c.next().map(|f| f.to_lowercase().chain(c).collect()).unwrap_or_default()+}+#[cfg(test)]mod tests {use super::*;diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rsindex 4ba84694..c9e6250c 100644--- a/src/server/mcp_runtime.rs+++ b/src/server/mcp_runtime.rs@@ -315,7 +315,7 @@ impl BrokerApprover {/// payment floor, Flight School or the production floor wants a card (exactly as in/// [`Self::classified`]), it names kwnt's secrets, or the grant was used or expired.async fn granted(&self, req: &ToolApprovalRequest, grant: &mcp::PrepushGrant) -> Option<Option<String>> {- if req.payment.is_some() || mcp::payment_floor::reason(req, None).is_some() {+ if req.payment.is_some() || mcp::payment_floor::reason(req, None).is_some() || credit_floor(&self.db, req).await.is_some() {return None;}if home_floor(&self.db, req).await {@@ -356,7 +356,10 @@ impl BrokerApprover {let mode = self.db.kwant_approvals(&req.kwant_id).await.ok();// The payment floor (D8): a call that pays always gets a card, whatever the approvals,// "Ask only when risky" or "always allow" say. Allowing it covers this one call.- let payment = req.payment.clone().or_else(|| mcp::payment_floor::reason(&req, None));+ let payment = match req.payment.clone().or_else(|| mcp::payment_floor::reason(&req, None)) {+ Some(why) => Some(why),+ None => credit_floor(&self.db, &req).await,+ };// Flight School (C3): the bot's tier for this task can add a card, never remove one. It// skips approvals off and smart Allow; a session "always allow" still counts (D9).let tier = match payment {@@ -413,6 +416,10 @@ impl BrokerApprover {}if let Some(why) = &payment {details["payment_reason"] = json!(why);+ // 26h: the card says whose credits it uses instead of "a payment"+ if let Some(app) = mcp::payment_floor::CreditApp::of_reason(why) {+ details["credits"] = json!(app.label());+ }}if let Some(why) = &tier {details["tier_reason"] = json!(why);@@ -613,6 +620,25 @@ impl BrokerApprover {}}+/// 26h: why a call to a renamed credit app (FLUX, Picsart) asks: the bot's stored server with+/// this name is at the app's address ([`mcp::payment_floor::credits_reason`]). Calls kwnt runs+/// itself already carry the address in `req.payment`; this covers the ones an agent CLI asks+/// about by name only. `None` for kwnt's own and claude's built-in tools.+pub async fn credit_floor(db: &Database, req: &ToolApprovalRequest) -> Option<String> {+ if req.builtin.is_some() || req.server.is_empty() || req.server == mcp::SELF_SERVER_NAME {+ return None;+ }+ let servers = match db.list_active_mcp_servers_for_kwant(&req.kwant_id).await {+ Ok(servers) => servers,+ Err(e) => {+ tracing::warn!(error = %e, "could not read the bot's MCP servers for the credit check");+ return None;+ }+ };+ let server = servers.into_iter().find(|s| s.name == req.server)?;+ mcp::payment_floor::credits_reason(&server.name, server.url.as_deref(), &req.tool)+}+/// 27e: the names (in kwant) of the turn's `servers` that are Home Assistant's: by what each/// said on kwnt's last connection to it in this run, else by what its last test stored. A server/// kwnt never heard from isn't counted (the delivery check only adds a continuation for them).@@ -1179,6 +1205,14 @@ pub async fn prepare_turn_with_opts(// A dry run writes nothing, so it needs no pre-push cardlet approver: Arc<dyn ToolApprover> =if opts.rehearse.is_some() { approver } else { Arc::new(PrepushApprover { inner: approver, state: state.clone() }) };+ // 26h: files a tool returns are saved in the turn's chat (not in a dry run, which writes nothing)+ let media = match (&self_scope, &opts.rehearse) {+ (Some(scope), None) if scope.origin.is_some() => Some(Arc::new(super::attachments::ChatMedia {+ state: state.clone(),+ scope: scope.clone(),+ }) as Arc<dyn mcp::media::MediaSink>),+ _ => None,+ };let ctx = McpTurnContext {servers,approver,@@ -1200,6 +1234,7 @@ pub async fn prepare_turn_with_opts(},records: Default::default(),kwnt_only: opts.every_call,+ media,};let session = PermissionSession::new(kwant.id.clone(), kwant.name.clone(), turn_id, ctx.clone(), cwd);state.mcp_sessions.lock().await.insert(token.clone(), session);@@ -1513,15 +1548,36 @@ pub async fn permission_endpoint(}}+/// 26h D3: the largest hook payload kwnt reads. A claude PostToolUse for an MCP tool carries the+/// pictures it returned as base64 (a 20 MB image is ~27 MB); past this the hook gets a 413, which+/// its `curl -f` turns into no output, and claude keeps its own output (nothing is saved).+pub const HOOK_BODY_LIMIT: usize = 64 * 1024 * 1024;+/// `POST /api/mcp/permission/:token/hook`: claude's PreToolUse, PostToolUse and/// PostToolUseFailure hooks for this turn's built-in tools ([`mcp::cli_hooks`]). Answers a/// PreToolUse deny when the same call already failed 3 times the same way, and nothing otherwise/// (204). An unknown token is a 404, which the hook's `curl -f` turns into no output: the call runs.+/// 26h D3: a PostToolUse for one of the bot's MCP tools saves the files in its result in the+/// turn's chat ([`mcp::media::finish_claude`]) and answers the text the model reads instead.pub async fn permission_hook_endpoint(State(state): State<AppState>, Path(token): Path<String>, Json(msg): Json<Value>) -> Response {let session = state.mcp_sessions.lock().await.get(&token).cloned();let Some(session) = session else {return StatusCode::NOT_FOUND.into_response();};+ if let Some((server, tool)) = mcp::cli_hooks::mcp_call(&msg) {+ let Some(cfg) = session.ctx.servers.iter().find(|s| s.name == server && mcp::cli_hooks::saves_media_for(server)) else {+ return StatusCode::NO_CONTENT.into_response();+ };+ let dir = mcp::cli_hooks::tool_results_dir(&msg);+ let media = session.ctx.media.as_deref();+ return match mcp::media::finish_claude(&msg["tool_response"], server, cfg.url.as_deref(), tool, media, dir.as_deref()).await {+ Some(text) => {+ tracing::info!(kwant = %session.kwant_id, turn = %session.turn_id, %server, %tool, "saved a claude MCP tool's files in the chat");+ Json(mcp::cli_hooks::replace_output(&text)).into_response()+ }+ None => StatusCode::NO_CONTENT.into_response(),+ };+ }match mcp::cli_hooks::on_event(&session.repeats, &msg) {Some(out) => {tracing::info!(kwant = %session.kwant_id, turn = %session.turn_id, "repeat guard: a claude tool call was denied");@@ -2007,6 +2063,7 @@ mod declined_tests {approvals: mcp::Approvals::Ask,records: Default::default(),kwnt_only: false,+ media: None,};let (session, problems) = McpToolSession::open(&ctx, None).await;assert!(problems.is_empty(), "{problems:?}");diff --git a/src/server/mod.rs b/src/server/mod.rsindex 7c11ee5d..475fe2de 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -468,7 +468,10 @@ pub fn create_router(state: AppState) -> Router {.route("/api/mcp/oauth/client.json", get(mcp_oauth::client_document)).route("/api/kwants/:id/mcp-servers", get(mcp_routes::get_kwant_servers).put(mcp_routes::set_kwant_servers)).route("/api/mcp/permission/:token", post(mcp_runtime::permission_endpoint))- .route("/api/mcp/permission/:token/hook", post(mcp_runtime::permission_hook_endpoint))+ .route(+ "/api/mcp/permission/:token/hook",+ post(mcp_runtime::permission_hook_endpoint).layer(axum::extract::DefaultBodyLimit::max(mcp_runtime::HOOK_BODY_LIMIT)),+ ).route("/api/mcp/gateway", post(mcp_runtime::gateway_endpoint)).route("/api/mcp/gateway/grok", post(mcp_runtime::gateway_grok_endpoint)).route("/api/mcp/self", post(continuity::self_endpoint))diff --git a/src/server/routes.rs b/src/server/routes.rsindex 86dbfada..ab9a2eb6 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -3210,18 +3210,19 @@ async fn run_kwant_turn_inner(purpose: opts.purpose.clone(),every_call: opts.every_call,};- // A no-tools turn starts no MCP server, kwant's own included+ // A no-tools turn starts no MCP server, kwant's own included. Boxed (26h): inline, its+ // future (now with the chat's media sink) grew this turn's past the test thread's stacklet mcp_turn = if opts.no_tools {None} else {- super::mcp_runtime::prepare_turn_with_opts(+ Box::pin(super::mcp_runtime::prepare_turn_with_opts(state,target_kwant,Some(tag.turn_id.clone()),workspace_dir.clone(),self_scope,card_opts,- )+ )).await};let mcp_ctx = mcp_turn.as_ref().map(|(ctx, _)| ctx.clone());diff --git a/tests/agents_in_vm_adversarial_test.rs b/tests/agents_in_vm_adversarial_test.rsindex c6a4c204..78d0da60 100644--- a/tests/agents_in_vm_adversarial_test.rs+++ b/tests/agents_in_vm_adversarial_test.rs@@ -486,6 +486,7 @@ async fn approval_turn(name: &str, answer: bool) -> (Vec<String>, bool, usize, Sapprovals: kwnt::mcp::Approvals::Ask,records: Default::default(),kwnt_only: false,+ media: None,};state.mcp_sessionsdiff --git a/tests/common/mod.rs b/tests/common/mod.rsindex 7e47e8ff..afce4967 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -25,6 +25,11 @@//! - `FAILSTEP:<tag>` / `BLOCKSTEP:<tag>` / `WAITSTEP:<tag>` in the current request (not the//! history): run a Bash tool step that fails, then end on a plan ("I'll retry the render…") / on a//! `Blocked:` line / waiting on the person in prose ("If you approve the command, …").+//! - `MCPHOOK:<base64 json>` (`{"server", "tool", "response"}`, [`mcp_hook_marker`]): as claude+//! does after the bot's MCP tool ran, run each `PostToolUse` hook in `--settings` whose matcher+//! fits `mcp__<server>__<tool>`, with claude's payload (`tool_response` = `response`) on stdin,+//! and reply `HOOKS[<n run>] MODELSAW[<what the model reads: the hook's updatedMCPToolOutput, or+//! the response>]`; once per marker.//! - `STREAMLINES:<base64 text>`: print that text (claude `stream-json` lines: an init line, tool//! calls and their results) before the reply; once per marker.//!@@ -169,6 +174,31 @@ if tt:print(json.dumps({"type": "result", "is_error": False, "num_turns": 1, "result": " ".join(out)}))sys.exit(0)reply = []+# MCPHOOK:<base64 json>: claude's PostToolUse hooks for one of the bot's MCP tools, once per marker+mh = re.findall(r"MCPHOOK:([A-Za-z0-9+/=]+)", prompt)+if mh:+ import hashlib, subprocess+ mh_flag = os.path.join(os.path.dirname(out_dir), "hooked-" + hashlib.sha1(mh[-1].encode()).hexdigest())+ if not os.path.exists(mh_flag):+ open(mh_flag, "w").close()+ c = json.loads(base64.b64decode(mh[-1]))+ name = "mcp__%s__%s" % (c["server"], c["tool"])+ payload = {"session_id": "s1", "transcript_path": c.get("transcript_path", ""), "cwd": os.getcwd(),+ "hook_event_name": "PostToolUse", "tool_name": name, "tool_input": {}, "tool_response": c["response"],+ "tool_use_id": "toolu_mcphook", "mcp_server": {"name": c["server"], "source": "dynamic"}}+ settings = json.loads(args[args.index("--settings") + 1]) if "--settings" in args else {}+ seen, ran = c["response"], 0+ for entry in settings.get("hooks", {}).get("PostToolUse", []):+ if re.search(entry.get("matcher", ""), name):+ for h in entry["hooks"]:+ ran += 1+ out = subprocess.run(h["command"], shell=True, input=json.dumps(payload).encode(),+ capture_output=True, timeout=h.get("timeout", 60)).stdout+ if out.strip():+ o = json.loads(out).get("hookSpecificOutput", {})+ seen = o.get("updatedMCPToolOutput", seen)+ reply.append("HOOKS[%d]" % ran)+ reply.append("MODELSAW[" + "|".join(p.get("text", p.get("type", "")) for p in seen) + "]")m = ([None] + list(re.finditer(r"CALLTOOL:([a-z_]+):([A-Za-z0-9+/=]+)", prompt)))[-1]done = Noneif m:@@ -272,6 +302,14 @@ pub fn call_tool_marker(tool: &str, args: Value) -> String {format!("CALLTOOL:{tool}:{}", base64::engine::general_purpose::STANDARD.encode(args.to_string()))}+/// A prompt marker that makes the fake CLI run its `PostToolUse` hooks for `mcp__<server>__<tool>`+/// with claude's `tool_response` `response` (26h D3).+pub fn mcp_hook_marker(server: &str, tool: &str, response: Value) -> String {+ use base64::Engine;+ let c = json!({"server": server, "tool": tool, "response": response});+ format!("MCPHOOK:{}", base64::engine::general_purpose::STANDARD.encode(c.to_string()))+}+/// A prompt marker that makes the fake CLI print these `stream-json` lines before its reply.pub fn stream_lines_marker(lines: &[Value]) -> String {use base64::Engine;diff --git a/tests/grok_driver_test.rs b/tests/grok_driver_test.rsindex aa59de44..791e2cb8 100644--- a/tests/grok_driver_test.rs+++ b/tests/grok_driver_test.rs@@ -333,6 +333,7 @@ fn mcp_ctx(dir: &Path) -> McpTurnContext {approvals: kwnt::mcp::Approvals::Ask,records: Default::default(),kwnt_only: false,+ media: None,}}diff --git a/tests/mcp_api_loop_test.rs b/tests/mcp_api_loop_test.rsindex 72ae83ac..bd2ed6bc 100644--- a/tests/mcp_api_loop_test.rs+++ b/tests/mcp_api_loop_test.rs@@ -93,6 +93,7 @@ fn ctx(approver: Arc<dyn ToolApprover>, timeout_secs: i64, max: usize) -> McpTurapprovals: kwnt::mcp::Approvals::Ask,records: Default::default(),kwnt_only: false,+ media: None,}}diff --git a/tests/mcp_gateway_test.rs b/tests/mcp_gateway_test.rsindex 39bc7993..c1bfe469 100644--- a/tests/mcp_gateway_test.rs+++ b/tests/mcp_gateway_test.rs@@ -72,6 +72,7 @@ async fn register(state: &AppState, token: &str, approver: Arc<dyn ToolApprover>approvals: kwnt::mcp::Approvals::Ask,records: Default::default(),kwnt_only: false,+ media: None,};state.mcp_sessions.lock().await.insert(token.into(),@@ -265,6 +266,7 @@ async fn ending_the_turn_cancels_a_call_waiting_for_its_card() {approvals: kwnt::mcp::Approvals::Ask,records: Default::default(),kwnt_only: false,+ media: None,};state.mcp_sessionsdiff --git a/tests/mcp_media_test.rs b/tests/mcp_media_test.rsnew file mode 100644index 00000000..748c6fb2--- /dev/null+++ b/tests/mcp_media_test.rs@@ -0,0 +1,287 @@+//! 26h: pictures an MCP tool returns are saved in the turn's chat as the bot's files and named for+//! the model, and paid generations (FLUX, Picsart credits) always ask. The FLUX-shaped tools of+//! `kwnt mcp-echo-server --media-tools` play Black Forest Labs' app, offline: no BFL or Picsart call.++mod common;++use async_trait::async_trait;+use common::*;+use kwnt::{+ broker::ApprovalDecision,+ db::{models::McpServer, spaces::SpaceId},+ drivers::events::RuntimeEvent,+ mcp::{+ session::{Caller, McpToolSession},+ ApprovalOutcome, McpTurnContext, ToolApprovalRequest, ToolApprover,+ },+ server::{+ attachments::ChatMedia,+ continuity::{SelfScope, TurnOrigin},+ mcp_runtime::BrokerApprover,+ },+};+use serde_json::{json, Value};+use std::{+ collections::BTreeMap,+ sync::{Arc, Mutex},+ time::Duration,+};++/// Allows every call and keeps the payment reason each was asked with.+#[derive(Default)]+struct Recording(Mutex<Vec<(String, Option<String>)>>);++#[async_trait]+impl ToolApprover for Recording {+ async fn approve(&self, req: ToolApprovalRequest) -> bool {+ self.0.lock().unwrap().push((req.tool.clone(), req.payment.clone()));+ true+ }+}++fn echo(name: &str) -> McpServer {+ McpServer {+ id: String::new(),+ name: name.into(),+ transport: "stdio".into(),+ command: Some(env!("CARGO_BIN_EXE_kwnt").into()),+ args: vec!["mcp-echo-server".into(), "--media-tools".into(), "--server-name".into(), name.into()],+ url: None,+ env: BTreeMap::new(),+ headers: BTreeMap::new(),+ enabled: true,+ timeout_secs: 10,+ created_at: None,+ }+}++fn scope(env: &Env) -> SelfScope {+ SelfScope {+ kwant_id: env.a.clone(),+ kwant_name: "A".into(),+ origin: Some(TurnOrigin { direct_kwant_id: Some(env.a.clone()), ..Default::default() }),+ turn_id: Some("t-media".into()),+ ..Default::default()+ }+}++fn ctx(env: &Env, server: McpServer, approver: Arc<dyn ToolApprover>, chat: bool) -> McpTurnContext {+ McpTurnContext {+ servers: vec![server],+ approver,+ config_dir: std::env::temp_dir(),+ permission_url: None,+ gateway: None,+ max_tool_iterations: 10,+ approvals: kwnt::mcp::Approvals::Ask,+ records: Default::default(),+ kwnt_only: false,+ media: chat.then(|| Arc::new(ChatMedia { state: env.state.clone(), scope: scope(env) }) as Arc<dyn kwnt::mcp::media::MediaSink>),+ }+}++fn caller(env: &Env) -> Caller {+ Caller { kwant_id: env.a.clone(), kwant_name: "A".into(), turn_id: "t-media".into() }+}++/// The bot's file messages in its direct chat: (text, meta).+async fn shared_files(env: &Env) -> Vec<(String, Value)> {+ messages(env, &env.a)+ .await+ .into_iter()+ .filter_map(|m| {+ let meta: Value = serde_json::from_str(m.meta.as_deref()?).ok()?;+ (meta["kind"] == "file").then_some((m.text, meta))+ })+ .collect()+}++#[tokio::test]+async fn flux_pictures_are_saved_in_the_chat_and_named_for_the_model() {+ let env = setup().await;+ let approver = Arc::new(Recording::default());+ let (session, problems) = McpToolSession::open(&ctx(&env, echo("flux"), approver.clone(), true), None).await;+ assert!(problems.is_empty(), "{problems:?}");++ let out = session.call(&caller(&env), "c1", "mcp__flux__generate_image", r#"{"prompt": "a red fox", "count": 2}"#).await;+ assert_eq!(out.status, "ok", "{}", out.text);+ let lines: Vec<&str> = out.text.lines().collect();+ assert_eq!(lines[0], "Generated 2 image(s) for: a red fox");+ assert!(lines[1].starts_with("Image saved in this chat as flux-generate_image-1.png (id "), "{}", out.text);+ assert!(lines[2].starts_with("Image saved in this chat as flux-generate_image-2.png (id "), "{}", out.text);+ // The model and the record never carry the base64 ("iVBOR" starts every PNG's)+ assert!(!out.text.contains("iVBOR"));+ assert!(!out.record.to_string().contains("iVBOR"));+ assert!(out.record.to_string().contains("flux-generate_image-1.png"), "{}", out.record);++ let files = shared_files(&env).await;+ assert_eq!(files.len(), 2, "{files:?}");+ for (text, meta) in &files {+ assert!(text.starts_with("Shared a file: flux-generate_image-"), "{text}");+ assert_eq!(meta["auto"], true);+ assert_eq!(meta["made_with"], "flux", "{meta}");+ assert_eq!(meta["turn_id"], "t-media");+ assert_eq!(meta["attachments"][0]["mime"], "image/png", "{meta}");+ }++ // The same pictures again: already in the chat, nothing posted twice+ let again = session.call(&caller(&env), "c2", "mcp__flux__generate_image", r#"{"prompt": "a red fox", "count": 2}"#).await;+ assert!(again.text.contains("Image already in this chat as flux-generate_image-1.png"), "{}", again.text);+ assert_eq!(shared_files(&env).await.len(), 2);++ // A read: no payment, and its text comes through as it is+ let credits = session.call(&caller(&env), "c3", "mcp__flux__get_credits", "{}").await;+ assert_eq!(credits.text, r#"{"credits": 412.5}"#);++ let asked = approver.0.lock().unwrap().clone();+ assert_eq!(asked[0], ("generate_image".to_string(), Some("generate_image uses your Black Forest Labs credits".to_string())));+ assert_eq!(asked[2], ("get_credits".to_string(), None));+ session.shutdown().await;+}++#[tokio::test]+async fn without_a_chat_the_model_hears_the_picture_wasnt_saved() {+ let env = setup().await;+ let approver = Arc::new(Recording::default());+ let (session, _) = McpToolSession::open(&ctx(&env, echo("flux"), approver, false), None).await;+ let out = session.call(&caller(&env), "c1", "mcp__flux__generate_image", r#"{"prompt": "x"}"#).await;+ assert_eq!(+ out.text,+ "Generated 1 image(s) for: x\n[image: image/png] An image came back but couldn't be saved: this turn has no chat to save it in."+ );+ assert!(shared_files(&env).await.is_empty());+ session.shutdown().await;+}++#[tokio::test]+async fn another_app_that_makes_pictures_is_not_a_payment_but_its_pictures_still_save() {+ let env = setup().await;+ let approver = Arc::new(Recording::default());+ let (session, _) = McpToolSession::open(&ctx(&env, echo("shop"), approver.clone(), true), None).await;+ let out = session.call(&caller(&env), "c1", "mcp__shop__generate_image", r#"{"prompt": "a mug"}"#).await;+ assert!(out.text.contains("Image saved in this chat as shop-generate_image-1.png"), "{}", out.text);+ assert_eq!(approver.0.lock().unwrap()[0], ("generate_image".to_string(), None));+ session.shutdown().await;+}++fn approver(env: &Env) -> BrokerApprover {+ BrokerApprover {+ db: env.state.db.clone(),+ data_dir: env.state.config.data_dir.clone(),+ broker: env.state.broker.clone(),+ events: env.state.event_sender.clone(),+ timeout: Duration::from_millis(300),+ conversation: env.a.clone(),+ chat: None,+ always_ask: false,+ strict_ask: false,+ started_by: None,+ }+}++/// A call to `server`'s `tool` the way an agent CLI asks it: no payment reason of its own.+fn cli_call(env: &Env, server: &str, tool: &str) -> ToolApprovalRequest {+ ToolApprovalRequest {+ kwant_id: env.a.clone(),+ kwant_name: "A".into(),+ turn_id: "t-media".into(),+ tool_name: format!("mcp__{server}__{tool}"),+ server: server.into(),+ tool: tool.into(),+ arguments: json!({"prompt": "a fox"}),+ builtin: None,+ smart: None,+ payment: None,+ }+}++/// A renamed BFL server (`images` at mcp.bfl.ai): its generations ask with approvals off and a+/// session grant, the card says whose credits, and "always this session" covers one call.+#[tokio::test]+async fn a_renamed_bfl_server_still_asks_and_the_card_names_the_credits() {+ let env = setup().await;+ let mut server = echo("images");+ server.transport = "http".into();+ server.command = None;+ server.args = vec![];+ server.url = Some("https://mcp.bfl.ai".into());+ let server = env.state.db.create_mcp_server(&SpaceId::default_space(), &server).await.unwrap();+ env.state.db.set_kwant_mcp_servers(&env.a, std::slice::from_ref(&server.id)).await.unwrap();+ env.state.db.set_kwant_approvals(&env.a, "off").await.unwrap();+ let a = env.a.clone();+ env.state.broker.allow_for_session(&a, &a, "mcp__images__generate_image").await;++ // A read runs without a card+ assert_eq!(approver(&env).decide(cli_call(&env, "images", "get_credits")).await, ApprovalOutcome::Allowed);++ // A generation asks; the card names the credits and never a price+ for decision in [ApprovalDecision::AlwaysAllowSession, ApprovalDecision::AllowOnce] {+ let mut events = env.state.event_sender.subscribe();+ let ap = Arc::new(approver(&env));+ let req = cli_call(&env, "images", "generate_image");+ let pending = tokio::spawn(async move { ap.decide(req).await });+ let (id, details) = loop {+ if let RuntimeEvent::ApprovalRequired { id, details, .. } = events.recv().await.unwrap() {+ break (id, details);+ }+ };+ assert_eq!(details["credits"], "Black Forest Labs", "{details}");+ assert_eq!(details["payment_reason"], "generate_image uses your Black Forest Labs credits");+ assert!(!details.to_string().contains('$'));+ assert!(env.state.broker.resolve(&id, decision).await);+ assert_eq!(pending.await.unwrap(), ApprovalOutcome::Allowed);+ }+}++/// 26h D3 (Rigel's QA of #780): on the claude engine claude calls the bot's servers itself, so a+/// picture reaches kwnt only through claude's PostToolUse hook. A whole claude turn with a FLUX+/// server: the fake claude runs the hooks kwnt's `--settings` gives it, with the payload claude+/// 2.1.326 sent for a PNG (Nov 17), through the real hook command and route. The picture ends up+/// as the bot's file in the chat, and the model reads its saved line, not the base64.+#[cfg(unix)] // the hook command is `sh -c "curl … || true"`, as claude runs it+#[tokio::test]+async fn a_claude_engine_tool_picture_is_saved_in_the_chat() {+ use base64::Engine;+ let env = setup().await;+ env.state.db.create_mcp_server(&SpaceId::default_space(), &echo("flux")).await.unwrap();+ // A 1×1 PNG+ let png = base64::engine::general_purpose::STANDARD.encode(PNG_1X1);+ let response = json!([+ {"type": "text", "text": "Here is your picture."},+ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": png}},+ {"type": "text", "text": "[Image: source: /home/o/.claude/projects/-w/s1/tool-results/mcp-flux-blob-1794927710294-86qnbo.png]"}+ ]);+ let marker = mcp_hook_marker("flux", "generate_image", response);+ send_direct(&env, &env.a, &format!("make a fox {marker} REPLYTAG:d3claude"), json!({})).await;+ let reply = wait_reply(&env, &env.a, "answer d3claude").await;++ // kwnt gave claude the media hook, and claude's model read the saved line instead of the picture+ assert!(reply.text.contains("HOOKS[1]"), "{}", reply.text);+ assert!(+ reply.text.contains("MODELSAW[Here is your picture.\nImage saved in this chat as flux-generate_image-1.png (id "),+ "{}",+ reply.text+ );+ assert!(!reply.text.contains("iVBOR") && !reply.text.contains("tool-results"), "{}", reply.text);+ let launch = invocations_with("d3claude").pop().unwrap();+ assert!(launch.contains(kwnt::mcp::cli_hooks::MCP_MATCHER), "{launch}");++ // The picture is the bot's file in the chat, made with flux+ let files = shared_files(&env).await;+ assert_eq!(files.len(), 1, "{files:?}");+ let (text, meta) = &files[0];+ assert!(text.starts_with("Shared a file: flux-generate_image-1.png"), "{text}");+ assert_eq!(meta["auto"], true);+ assert_eq!(meta["made_with"], "flux", "{meta}");+ assert_eq!(meta["attachments"][0]["mime"], "image/png", "{meta}");+ let id = meta["attachments"][0]["id"].as_str().unwrap();+ assert!(reply.text.contains(&format!("(id {id})")), "the model names the saved file: {}", reply.text);+}++#[cfg(unix)] // only the claude-engine test above uses it+const PNG_1X1: &[u8] = &[+ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01,+ 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x44, 0x41,+ 0x54, 0x78, 0x9C, 0x63, 0xF8, 0xCF, 0xC0, 0xF0, 0x1F, 0x00, 0x05, 0x00, 0x01, 0xFF, 0x89, 0x99, 0x3D, 0x1D, 0x00, 0x00,+ 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,+];diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rsindex 1ccf9549..28fb7a56 100644--- a/tests/mcp_runtime_test.rs+++ b/tests/mcp_runtime_test.rs@@ -56,6 +56,7 @@ fn ctx(dir: &std::path::Path, approver: Arc<dyn ToolApprover>) -> McpTurnContextapprovals: kwnt::mcp::Approvals::Ask,records: Default::default(),kwnt_only: false,+ media: None,}}diff --git a/tests/prepush_test.rs b/tests/prepush_test.rsindex b8003315..02c9e4d3 100644--- a/tests/prepush_test.rs+++ b/tests/prepush_test.rs@@ -552,6 +552,7 @@ async fn kwants_own_github_tools_go_through_the_pre_push_card() {approvals: kwnt::mcp::Approvals::Ask,records: Default::default(),kwnt_only: false,+ media: None,};let session = kwnt::server::mcp_runtime::PermissionSession::new(env.a.clone(), "A".into(), "gh-turn".into(), ctx, None);env.state.mcp_sessions.lock().await.insert("gh-tok".into(), session);diff --git a/tests/repeat_guard_test.rs b/tests/repeat_guard_test.rsindex 998315dd..c5899a39 100644--- a/tests/repeat_guard_test.rs+++ b/tests/repeat_guard_test.rs@@ -105,6 +105,7 @@ fn ctx(url: &str, approver: Arc<dyn ToolApprover>, max: usize) -> McpTurnContextapprovals: kwnt::mcp::Approvals::Ask,records: Default::default(),kwnt_only: false,+ media: None,}}diff --git a/tests/transcribe_test.rs b/tests/transcribe_test.rsindex 9e3ed1b7..db2ac13a 100644--- a/tests/transcribe_test.rs+++ b/tests/transcribe_test.rs@@ -502,6 +502,7 @@ async fn an_mcp_session_token_is_refused() {approvals: kwnt::mcp::Approvals::Ask,records: Default::default(),kwnt_only: false,+ media: None,};state.mcp_sessions.lock().await.insert("mcp-turn".into(), PermissionSession::new("k1".into(), "Ada".into(), "t1".into(), ctx, None));let mut req = audio_post(DEF, "", "audio/webm", vec![1; 10]);