Plus ไม่มี API
ถ้า
มี ChatGPT Plus อยู่
ChatGPT Plus และ Gemini Pro เป็น
แถว
| วิธี | อัตโนมัติ | ค่าใช้จ่าย | ข้อสังเกต |
|---|---|---|---|
| สร้างภาพ | ✓ได้ | เครดิต Magnific | เสถียร |
| Claude ใช้ | บางส่วน | แพ็กเกจ | ช้า พัง |
| Claude ควบคุม | บางส่วน | แพ็กเกจ | ข้อเสีย |
| API ของ OpenAI หรือ Gemini โดยตรง | ✓ได้ | จ่าย | ซ้ำซ้อน |
| สร้างภาพ | ✕ไม่ | แพ็กเกจ | ปลอดภัย |
| ต่อ Codex เข้ากับ Claude เป็น | ✓ได้ | โควตา Plus | ทาง |
Claude สั่ง codex exec ผ่าน Terminal | ✓ได้ | โควตา Plus | ใน Cowork ระบบ |
| Claude เขียน Prompt ไว้ แล้ว | กึ่ง | โควตา Plus | เริ่ม |
Claude Cowork ทำงานcodex-image-mcp.js ที่
ส่ง Prompt ทุก
แปลง
วาด
ดึง
Claude ไม่ได้ “เข้าไป ต่างใช้” ChatGPT แต่ สั่งงาน ผ่าน เครื่องมือ ทางการ ของ OpenAI ที่ รัน บน คอม คุณ เอง จึง ใช้ โควตา Plus ได้ ตรง ๆ จาก การ ให้ AI กด หน้า เว็บ แทน คน ซึ่ง ช้า และ ขัดข้อตกลงการใช้งาน
เปิด
ใช้
ใช้
สร้าง Videos\AI-Images ไว้
ติดตั้ง ล็อกอิน วาง
ติดตั้ง Node.js เวอร์ชัน LTS แล้ว
npm install -g @openai/codex codex --version
เบราว์เซอร์
codex login
บันทึกcodex-image-mcp.js ไว้Videos\AI-Images
ไป<ชื่อผู้ใช้> เป็น
"mcpServers": {
"codex": {
"command": "C:\\Program Files\\nodejs\\node.exe",
"args": ["C:\\Users\\<ชื่อผู้ใช้>\\Videos\\AI-Images\\codex-image-mcp.js"]
}
},คลิก
codex ในcodex_check เพื่อสร้างภาพ 1 ภาพ กำหนด
สร้าง
รอ
บอก
ตัวเชื่อม
codex exec ด้วย sandbox แบบ workspace-write เขียนClaude เขียนgenerate_image_set โดย
| ขั้นตอน | ใช้ | ผล |
|---|---|---|
| บท | Claude | 6 บรรทัด 6 ฉาก ไม่ |
| ภาพ | Codex ผ่าน generate_image_set | 6 ภาพ 941×1672 ใช้เวลา |
| เสียง | Gemini TTS เสียง Achird | สร้าง |
| เพลง | เขียน | เปียโน |
| ตัดต่อ | Python + ffmpeg | ซูม |
codex mcp-server ออก--full-auto ก็codex-image-mcp.js ที่codex exec แทนgenerate_image_set สร้างreference_images.js ต้อง Quit แอข้อมูล
/status ใน Codexตัวเชื่อมcodex-image-mcp.log ใน
#!/usr/bin/env node
// codex-image-mcp.js — a tiny MCP server (stdio) that lets Claude ask Codex CLI to generate images.
// No dependencies. Uses the ChatGPT login of the installed Codex CLI (`codex exec` + $imagegen).
// Images are saved to %USERPROFILE%\Videos\AI-Images. Diagnostics go to codex-image-mcp.log next to this file.
'use strict';
const { spawn, execFileSync } = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');
const readline = require('readline');
const HOME = process.env.USERPROFILE || os.homedir();
const OUT_DIR = path.join(HOME, 'Videos', 'AI-Images');
const GEN_DIR = path.join(HOME, '.codex', 'generated_images');
const LOG = path.join(__dirname, 'codex-image-mcp.log');
function log(...parts) {
try { fs.appendFileSync(LOG, `[${new Date().toISOString()}] ${parts.join(' ')}\n`); } catch (_) {}
}
function findCodexJs() {
const candidates = [
path.join(process.env.APPDATA || path.join(HOME, 'AppData', 'Roaming'), 'npm', 'node_modules', '@openai', 'codex', 'bin', 'codex.js'),
];
for (const c of candidates) if (fs.existsSync(c)) return c;
return null;
}
const CODEX_JS = findCodexJs();
log('server start; node', process.version, '; codex.js =', CODEX_JS || 'NOT FOUND');
function runCodexSync(args, timeoutMs = 30000) {
if (!CODEX_JS) throw new Error('Codex CLI not found (expected %APPDATA%\\npm\\node_modules\\@openai\\codex\\bin\\codex.js)');
try {
return execFileSync(process.execPath, [CODEX_JS, ...args], {
encoding: 'utf8', timeout: timeoutMs, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],
});
} catch (e) {
return String(e.stdout || '') + String(e.stderr || '') + (e.message ? `\n${e.message}` : '');
}
}
let execHelpCache = null;
function execHelp() {
if (execHelpCache === null) execHelpCache = runCodexSync(['exec', '--help']);
return execHelpCache;
}
// ---------- jobs ----------
const jobs = new Map();
let seq = 0;
function newestImageSince(dir, sinceMs, depth = 3) {
let best = null;
function walk(d, lvl) {
let entries;
try { entries = fs.readdirSync(d, { withFileTypes: true }); } catch (_) { return; }
for (const ent of entries) {
const p = path.join(d, ent.name);
if (ent.isDirectory()) { if (lvl < depth) walk(p, lvl + 1); continue; }
if (!/\.(png|jpe?g|webp)$/i.test(ent.name)) continue;
let st; try { st = fs.statSync(p); } catch (_) { continue; }
if (st.mtimeMs >= sinceMs && (!best || st.mtimeMs > best.mtimeMs)) best = { path: p, mtimeMs: st.mtimeMs };
}
}
walk(dir, 0);
return best;
}
function safeName(name) {
let fn = String(name || `image-${Date.now()}.png`).trim().replace(/[\\/:*?"<>|]/g, '_');
if (!/\.png$/i.test(fn)) fn = fn.replace(/\.(jpe?g|webp)$/i, '') + '.png';
return fn;
}
function resolveOutDir(subfolder) {
if (!subfolder) return OUT_DIR;
const clean = String(subfolder).replace(/[:*?"<>|]/g, '_').replace(/^[\\/]+/, '');
const dir = path.resolve(OUT_DIR, clean);
if (!dir.startsWith(path.resolve(OUT_DIR))) throw new Error('subfolder must stay inside AI-Images');
return dir;
}
function resolveRefs(refs, outDir) {
const list = [];
for (const r of refs || []) {
const cands = [path.resolve(outDir, r), path.resolve(OUT_DIR, r)];
const hit = cands.find((c) => c.startsWith(path.resolve(OUT_DIR)) && fs.existsSync(c));
if (!hit) throw new Error(`reference image not found inside AI-Images: ${r}`);
list.push(hit);
}
return list;
}
// items: [{filename, prompt}]
function startJob({ items, aspect_ratio, subfolder, reference_images, consistency_notes }) {
if (!CODEX_JS) throw new Error('Codex CLI not found');
if (!Array.isArray(items) || !items.length) throw new Error('no images requested');
for (const it of items) if (!it || !it.prompt || !String(it.prompt).trim()) throw new Error('every image needs a prompt');
const outDir = resolveOutDir(subfolder);
fs.mkdirSync(outDir, { recursive: true });
const refs = resolveRefs(reference_images, outDir);
const ar = aspect_ratio || '9:16';
const files = items.map((it) => ({ name: safeName(it.filename), prompt: String(it.prompt).trim() }));
let instruction;
const refNote = refs.length
? `Attached reference image(s): ${refs.map((r) => path.basename(r)).join(', ')}. Use them as the visual reference: keep the same character(s) (face, hair, body, clothing unless the scene says otherwise) and the same visual style.\n`
: '';
if (files.length === 1) {
instruction =
`Use $imagegen to create exactly one image with aspect ratio ${ar}.\n` + refNote +
(consistency_notes ? `Consistency notes: ${consistency_notes}\n` : '') +
`Image description: ${files[0].prompt}\n` +
`Save the final PNG in the current working folder as "${files[0].name}". ` +
`Do not create, modify or delete any other files. When done, reply with just the file name.`;
} else {
instruction =
`Use $imagegen to create a SET of ${files.length} images, one at a time, in the order listed, each with aspect ratio ${ar}.\n` +
`They are frames of ONE story and must look like the same film: the same character(s) with the same face, hair and build in every image, the same art style, colour grading and lighting quality. ` +
`After the first image, use the images you already generated in this session as visual references for the following ones.\n` + refNote +
(consistency_notes ? `Consistency notes (apply to every image): ${consistency_notes}\n` : '') +
files.map((f, i) => `Image ${i + 1} -> save as "${f.name}": ${f.prompt}`).join('\n') + '\n' +
`Save every final PNG in the current working folder with exactly those file names. ` +
`Do not create, modify or delete any other files. When done, reply with the list of file names.`;
}
const help = execHelp();
const args = ['exec'];
if (help.includes('--sandbox')) args.push('-s', 'workspace-write');
if (help.includes('--cd')) args.push('-C', outDir);
if (help.includes('--skip-git-repo-check')) args.push('--skip-git-repo-check');
if (refs.length) {
if (!help.includes('--image')) throw new Error('this Codex version cannot attach reference images to exec');
args.push('--image', ...refs, '--');
}
args.push(instruction);
const id = String(++seq);
const job = {
id, dir: outDir, files: files.map((f) => path.join(outDir, f.name)),
status: 'running', code: null, output: '', startedAt: Date.now(),
};
jobs.set(id, job);
const child = spawn(process.execPath, [CODEX_JS, ...args], {
cwd: outDir, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
});
const append = (d) => { job.output = (job.output + d.toString()).slice(-8000); };
child.stdout.on('data', append);
child.stderr.on('data', append);
child.on('error', (e) => { job.status = 'failed'; job.output += `\nspawn error: ${e.message}`; log('job', id, 'spawn error', e.message); });
child.on('close', (code) => {
job.code = code;
if (job.files.length === 1 && !fs.existsSync(job.files[0])) {
// Fallback: Codex may have left the image only in ~/.codex/generated_images
const found = newestImageSince(GEN_DIR, job.startedAt - 5000);
if (found) {
try { fs.copyFileSync(found.path, job.files[0]); job.copiedFrom = found.path; } catch (e) { job.output += `\ncopy failed: ${e.message}`; }
}
}
const made = job.files.filter((f) => fs.existsSync(f)).length;
job.status = made === job.files.length ? 'done' : made > 0 ? 'partial' : 'failed';
job.finishedAt = Date.now();
log('job', id, job.status, `${made}/${job.files.length}`, 'exit', code);
});
log('job', id, 'started', files.map((f) => f.name).join(','), 'refs:', refs.length, 'args:', args.slice(0, -1).join(' '));
return job;
}
function jobSummary(job, includeOutput) {
const s = {
job_id: job.id,
status: job.status,
folder: job.dir,
files: job.files.map((f) => ({ file: path.basename(f), exists: fs.existsSync(f) })),
seconds: Math.round(((job.finishedAt || Date.now()) - job.startedAt) / 1000),
};
if (job.code !== null) s.exit_code = job.code;
if (job.copiedFrom) s.copied_from = job.copiedFrom;
if (includeOutput || job.status === 'failed' || job.status === 'partial') s.codex_output_tail = job.output.slice(-2500);
return s;
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// ---------- tools ----------
const SUBFOLDER = { type: 'string', description: 'Optional subfolder inside Videos\\AI-Images (e.g. "story01"). Created if missing.' };
const REFS = { type: 'array', items: { type: 'string' }, description: 'Optional reference image file names (inside AI-Images or the subfolder) to keep the same character/style.' };
const TOOLS = [
{
name: 'generate_image',
description:
'Ask Codex CLI (ChatGPT Plus, gpt-image) to generate ONE image and save it as a PNG in the user\'s Videos\\AI-Images folder. ' +
'Optional reference_images keep a character consistent. Starts a background job and returns a job_id; then call image_job_status. ' +
'Usually 30-120 seconds per image.',
inputSchema: {
type: 'object',
properties: {
prompt: { type: 'string', description: 'Detailed description of the image (English works best).' },
filename: { type: 'string', description: 'Output file name, e.g. scene01.png. Existing files with the same name may be overwritten.' },
aspect_ratio: { type: 'string', description: 'e.g. 9:16 (default), 16:9, 1:1, 4:5' },
subfolder: SUBFOLDER,
reference_images: REFS,
},
required: ['prompt', 'filename'],
},
},
{
name: 'generate_image_set',
description:
'Generate SEVERAL images (e.g. story scenes) in ONE Codex session so the same character and style carry through every image. ' +
'Background job: returns a job_id; poll image_job_status. Takes roughly 1 minute per image.',
inputSchema: {
type: 'object',
properties: {
images: {
type: 'array',
description: 'Ordered list of images to create.',
items: {
type: 'object',
properties: { filename: { type: 'string' }, prompt: { type: 'string' } },
required: ['filename', 'prompt'],
},
},
consistency_notes: { type: 'string', description: 'Character/style description applied to every image.' },
aspect_ratio: { type: 'string', description: 'e.g. 9:16 (default)' },
subfolder: SUBFOLDER,
reference_images: REFS,
},
required: ['images'],
},
},
{
name: 'image_job_status',
description: 'Check (and optionally wait for) an image job. Waits up to wait_seconds (default 45, max 50) for it to finish.',
inputSchema: {
type: 'object',
properties: {
job_id: { type: 'string' },
wait_seconds: { type: 'number', description: 'How long to wait for completion before returning (0-50).' },
include_output: { type: 'boolean', description: 'Include the tail of Codex output.' },
},
required: ['job_id'],
},
},
{
name: 'codex_check',
description: 'Diagnostics: shows Codex CLI location, version, login status and supported exec options.',
inputSchema: { type: 'object', properties: {} },
},
];
function text(obj, isError = false) {
return { content: [{ type: 'text', text: typeof obj === 'string' ? obj : JSON.stringify(obj, null, 2) }], isError };
}
async function callTool(name, args) {
if (name === 'generate_image') {
const job = startJob({ items: [{ filename: args.filename, prompt: args.prompt }], ...args });
return text({ ...jobSummary(job), next: 'Call image_job_status with this job_id to wait for the image.' });
}
if (name === 'generate_image_set') {
const job = startJob({ items: args.images, ...args });
return text({ ...jobSummary(job), next: 'Call image_job_status with this job_id (repeat) until status is done.' });
}
if (name === 'image_job_status') {
const job = jobs.get(String(args.job_id));
if (!job) return text(`Unknown job_id ${args.job_id}`, true);
const waitMs = Math.max(0, Math.min(50, Number(args.wait_seconds ?? 45))) * 1000;
const until = Date.now() + waitMs;
while (job.status === 'running' && Date.now() < until) await sleep(1000);
return text(jobSummary(job, !!args.include_output), job.status === 'failed');
}
if (name === 'codex_check') {
return text({
node: process.version,
codex_js: CODEX_JS,
output_folder: OUT_DIR,
version: CODEX_JS ? runCodexSync(['--version']).trim() : null,
login_status: CODEX_JS ? runCodexSync(['login', 'status']).trim() : null,
exec_supports: CODEX_JS ? ['--sandbox', '--cd', '--skip-git-repo-check', '--image'].filter((o) => execHelp().includes(o)) : [],
});
}
return text(`Unknown tool: ${name}`, true);
}
// ---------- MCP stdio (newline-delimited JSON-RPC) ----------
function send(msg) { process.stdout.write(JSON.stringify(msg) + '\n'); }
const rl = readline.createInterface({ input: process.stdin });
rl.on('line', async (line) => {
line = line.trim();
if (!line) return;
let msg;
try { msg = JSON.parse(line); } catch (_) { log('bad json', line.slice(0, 200)); return; }
const { id, method, params } = msg;
if (id === undefined || id === null) return; // notification
try {
let result;
switch (method) {
case 'initialize':
result = {
protocolVersion: (params && params.protocolVersion) || '2025-06-18',
capabilities: { tools: {} },
serverInfo: { name: 'codex-image', version: '1.1.0' },
};
break;
case 'ping': result = {}; break;
case 'tools/list': result = { tools: TOOLS }; break;
case 'tools/call': result = await callTool(params && params.name, (params && params.arguments) || {}); break;
case 'resources/list': result = { resources: [] }; break;
case 'prompts/list': result = { prompts: [] }; break;
default:
send({ jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${method}` } });
return;
}
send({ jsonrpc: '2.0', id, result });
} catch (e) {
log('error in', method, e && e.stack);
send({ jsonrpc: '2.0', id, result: text(`Error: ${e.message}`, true) });
}
});
rl.on('close', () => { log('stdin closed, exiting'); process.exit(0); });
รวม