|
| 1 | +// intercept.ts — proxy response post-processing for image-generating MCPs. |
| 2 | +// |
| 3 | +// 上流 MCP が tool result の text content に「コンテナ内の絶対パス」を返してくる |
| 4 | +// ケースを救う層。/var/lib/openai-image-tmp 配下を image-hub-app から ro マウントで |
| 5 | +// 見えるようにしておき、proxy が tools/call レスポンスを buffer → SSE parse → |
| 6 | +// 該当 path を検出 → SHA256 prefix12 で artifact 化 → text を /files/<id> URL に |
| 7 | +// rewrite して再 emit する。 |
| 8 | +// |
| 9 | +// 設計判断: |
| 10 | +// - 対象は `tools/call` レスポンスのみ (tools/list 等の discovery は素通り) |
| 11 | +// - 上流 MCP の `Image` content block (base64) は触らない (Bell が画像を見て |
| 12 | +// 会話できる必要があるため、token cost は受容) |
| 13 | +// - file id = SHA256(content) prefix 12 文字 (collision 確率実用ゼロ、 |
| 14 | +// idempotent: 同じ画像なら ON CONFLICT で artifact upsert) |
| 15 | +// - file が見つからない / size が cap を超える / それ以外の I/O エラーは |
| 16 | +// silent ではなく log + 元の path を残す (fallback 禁止ルールに準拠) |
| 17 | +// |
| 18 | +// 拡張: REWRITE_RULES に upstream 名 → RewriteRule を追加すれば mermaid / |
| 19 | +// excalidraw も同じ仕組みに乗る (それぞれの path pattern を確認してから)。 |
| 20 | + |
| 21 | +import { createHash } from 'node:crypto'; |
| 22 | +import { copyFileSync, existsSync, mkdirSync, readFileSync, statSync } from 'node:fs'; |
| 23 | +import { extname, join } from 'node:path'; |
| 24 | +import type { Storage } from './storage.js'; |
| 25 | + |
| 26 | +export interface RewriteRule { |
| 27 | + pathPattern: RegExp; |
| 28 | + mimeByExt: Record<string, string>; |
| 29 | + maxFileBytes: number; |
| 30 | + project: string; |
| 31 | +} |
| 32 | + |
| 33 | +const OPENAI_IMAGE_RULE: RewriteRule = { |
| 34 | + // Python tempfile.mkdtemp(prefix="openai_gen_image_") が TMPDIR=/var/lib/openai-image-tmp |
| 35 | + // 配下に作る親ディレクトリ。子ファイル名は generated_xxx.{png,jpg,jpeg,webp} |
| 36 | + // (kazyam53/openai_gen_image_mcp の output_format 仕様に対応)。 |
| 37 | + pathPattern: /\/var\/lib\/openai-image-tmp\/openai_gen_image_[A-Za-z0-9_-]+\/[A-Za-z0-9._-]+\.(?:png|jpg|jpeg|webp)/g, |
| 38 | + mimeByExt: { |
| 39 | + '.png': 'image/png', |
| 40 | + '.jpg': 'image/jpeg', |
| 41 | + '.jpeg': 'image/jpeg', |
| 42 | + '.webp': 'image/webp', |
| 43 | + }, |
| 44 | + maxFileBytes: 32 * 1024 * 1024, |
| 45 | + project: 'openai-image', |
| 46 | +}; |
| 47 | + |
| 48 | +export const REWRITE_RULES: Readonly<Record<string, RewriteRule>> = Object.freeze({ |
| 49 | + 'openai-image': OPENAI_IMAGE_RULE, |
| 50 | +}); |
| 51 | + |
| 52 | +export interface InterceptDeps { |
| 53 | + storage: Storage; |
| 54 | + storageDir: string; |
| 55 | + publicFilesUrlBase: string; |
| 56 | + log: (msg: string) => void; |
| 57 | +} |
| 58 | + |
| 59 | +interface SseEvent { |
| 60 | + event: string; |
| 61 | + id: string; |
| 62 | + data: string; |
| 63 | +} |
| 64 | + |
| 65 | +function splitSseEvents(text: string): string[] { |
| 66 | + return text.split(/\r?\n\r?\n/); |
| 67 | +} |
| 68 | + |
| 69 | +function parseSseEvent(block: string): SseEvent | null { |
| 70 | + const lines = block.split(/\r?\n/); |
| 71 | + let event = 'message'; |
| 72 | + let id = ''; |
| 73 | + const dataLines: string[] = []; |
| 74 | + for (const line of lines) { |
| 75 | + if (line.startsWith(':')) continue; // SSE comment |
| 76 | + if (line.startsWith('event:')) event = line.slice(6).trim(); |
| 77 | + else if (line.startsWith('id:')) id = line.slice(3).trim(); |
| 78 | + else if (line.startsWith('data:')) { |
| 79 | + const v = line.slice(5); |
| 80 | + dataLines.push(v.startsWith(' ') ? v.slice(1) : v); |
| 81 | + } |
| 82 | + } |
| 83 | + if (dataLines.length === 0) return null; |
| 84 | + return { event, id, data: dataLines.join('\n') }; |
| 85 | +} |
| 86 | + |
| 87 | +function reEncodeSseEvent(ev: SseEvent): string { |
| 88 | + const lines: string[] = []; |
| 89 | + if (ev.event && ev.event !== 'message') lines.push(`event: ${ev.event}`); |
| 90 | + if (ev.id) lines.push(`id: ${ev.id}`); |
| 91 | + for (const dl of ev.data.split(/\r?\n/)) { |
| 92 | + lines.push(`data: ${dl}`); |
| 93 | + } |
| 94 | + return lines.join('\n') + '\n\n'; |
| 95 | +} |
| 96 | + |
| 97 | +interface ToolCallEnvelope { |
| 98 | + jsonrpc?: string; |
| 99 | + id?: number | string; |
| 100 | + result?: { |
| 101 | + content?: Array<{ type: string; text?: string; data?: string; mimeType?: string }>; |
| 102 | + [k: string]: unknown; |
| 103 | + }; |
| 104 | + error?: unknown; |
| 105 | + [k: string]: unknown; |
| 106 | +} |
| 107 | + |
| 108 | +function rewriteText(text: string, rule: RewriteRule, deps: InterceptDeps): { text: string; rewrites: number } { |
| 109 | + let rewrites = 0; |
| 110 | + const newText = text.replace(rule.pathPattern, (match) => { |
| 111 | + try { |
| 112 | + const st = statSync(match); |
| 113 | + if (!st.isFile()) { |
| 114 | + deps.log(`intercept: not a file, skip: ${match}`); |
| 115 | + return match; |
| 116 | + } |
| 117 | + if (st.size > rule.maxFileBytes) { |
| 118 | + deps.log(`intercept: file too large (${st.size} > ${rule.maxFileBytes}), skip: ${match}`); |
| 119 | + return match; |
| 120 | + } |
| 121 | + const buf = readFileSync(match); |
| 122 | + const sha = createHash('sha256').update(buf).digest('hex'); |
| 123 | + const id = sha.slice(0, 12); |
| 124 | + const ext = extname(match).toLowerCase(); |
| 125 | + const mime = rule.mimeByExt[ext] ?? 'application/octet-stream'; |
| 126 | + const fileName = `${id}${ext}`; |
| 127 | + const destPath = join(deps.storageDir, fileName); |
| 128 | + if (!existsSync(destPath)) { |
| 129 | + mkdirSync(deps.storageDir, { recursive: true }); |
| 130 | + copyFileSync(match, destPath); |
| 131 | + } |
| 132 | + deps.storage.putArtifact({ id, mime, project: rule.project }); |
| 133 | + rewrites += 1; |
| 134 | + const url = `${deps.publicFilesUrlBase.replace(/\/$/, '')}/${fileName}`; |
| 135 | + return url; |
| 136 | + } catch (e) { |
| 137 | + deps.log(`intercept: rewrite skip for ${match}: ${e instanceof Error ? e.message : String(e)}`); |
| 138 | + return match; |
| 139 | + } |
| 140 | + }); |
| 141 | + return { text: newText, rewrites }; |
| 142 | +} |
| 143 | + |
| 144 | +export function maybeRewriteSseBody(body: Buffer, ruleName: string, deps: InterceptDeps): Buffer { |
| 145 | + const rule = REWRITE_RULES[ruleName]; |
| 146 | + if (rule === undefined) return body; |
| 147 | + |
| 148 | + const text = body.toString('utf8'); |
| 149 | + const blocks = splitSseEvents(text); |
| 150 | + |
| 151 | + let totalRewrites = 0; |
| 152 | + const out: string[] = []; |
| 153 | + for (let i = 0; i < blocks.length; i += 1) { |
| 154 | + const block = blocks[i]; |
| 155 | + if (block === undefined || block.length === 0) { |
| 156 | + // SSE 末尾の空 chunk (input が "...\n\n" で終わっていた場合)。 |
| 157 | + // 区切りは reEncodeSseEvent が "\n\n" を付けるので、ここでは何も足さない。 |
| 158 | + continue; |
| 159 | + } |
| 160 | + const ev = parseSseEvent(block); |
| 161 | + if (ev === null) { |
| 162 | + out.push(block + '\n\n'); |
| 163 | + continue; |
| 164 | + } |
| 165 | + let parsed: ToolCallEnvelope | null = null; |
| 166 | + try { |
| 167 | + parsed = JSON.parse(ev.data) as ToolCallEnvelope; |
| 168 | + } catch { |
| 169 | + out.push(reEncodeSseEvent(ev)); |
| 170 | + continue; |
| 171 | + } |
| 172 | + const content = parsed.result?.content; |
| 173 | + if (!Array.isArray(content)) { |
| 174 | + out.push(reEncodeSseEvent(ev)); |
| 175 | + continue; |
| 176 | + } |
| 177 | + let touched = false; |
| 178 | + for (const item of content) { |
| 179 | + if (item.type === 'text' && typeof item.text === 'string') { |
| 180 | + const r = rewriteText(item.text, rule, deps); |
| 181 | + if (r.rewrites > 0) { |
| 182 | + item.text = r.text; |
| 183 | + touched = true; |
| 184 | + totalRewrites += r.rewrites; |
| 185 | + } |
| 186 | + } |
| 187 | + } |
| 188 | + if (touched) { |
| 189 | + out.push(reEncodeSseEvent({ ...ev, data: JSON.stringify(parsed) })); |
| 190 | + } else { |
| 191 | + out.push(reEncodeSseEvent(ev)); |
| 192 | + } |
| 193 | + } |
| 194 | + |
| 195 | + if (totalRewrites === 0) return body; |
| 196 | + deps.log(`intercept[${ruleName}]: rewrote ${totalRewrites} path(s) to /files URL`); |
| 197 | + return Buffer.from(out.join(''), 'utf8'); |
| 198 | +} |
| 199 | + |
| 200 | +export function shouldIntercept(name: string, reqBody: unknown): boolean { |
| 201 | + if (!(name in REWRITE_RULES)) return false; |
| 202 | + if (typeof reqBody !== 'object' || reqBody === null) return false; |
| 203 | + return (reqBody as { method?: unknown }).method === 'tools/call'; |
| 204 | +} |
0 commit comments