const MCP_SERVER_URL = 'https://black-forest-labs-flux-1-kontext-dev.hf.space/run/FLUX_1_Kontext_Dev_infer'; /** * Edits a bonsai image using the FLUX.1 Kontext MCP tool. * @param imageBase64 The base64 encoded string of the input image. * @param prompt The text prompt describing the desired edit. * @returns A base64 encoded string of the edited image, or null if an error occurs. */ export const editBonsaiWithKontext = async ( imageBase64: string, prompt: string ): Promise => { try { const inputImage = `data:image/jpeg;base64,${imageBase64}`; // Based on the provided documentation and common Gradio API structure. // The payload is an object with a 'data' array containing the arguments in order. // The order of arguments is assumed from the Python example: // input_image, prompt, seed, randomize_seed, guidance_scale const payload = { data: [ inputImage, // input_image prompt, // prompt -1, // seed (-1 for random) true, // randomize_seed 2.5, // guidance_scale ] }; const response = await fetch(MCP_SERVER_URL, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(payload), }); if (!response.ok) { const errorBody = await response.text(); console.error("MCP Server Error:", response.status, errorBody); throw new Error(`Request failed with status ${response.status}`); } const result = await response.json(); // Gradio API responses typically wrap the output in a 'data' array. // The edited image is expected to be the first element. if (result && Array.isArray(result.data) && result.data.length > 0) { const outputImage = result.data[0]; // The output is often a data URI. We need to extract the base64 part. if (typeof outputImage === 'string' && outputImage.startsWith('data:image/')) { return outputImage.split(',')[1]; } } console.error("Invalid response format from MCP server:", result); return null; } catch (error) { console.error("Error calling MCP tool:", error); return null; } };