import { initStderrTee } from "../../../../lib/mcp-stderr-tee/dist/index.js";
initStderrTee("replicate");
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { readToken, writeToken, validateToken } from "./lib/replicate-key.js";
import { imageGenerate } from "./tools/image-generate.js";
const ACCOUNT_ID = process.env.ACCOUNT_ID;
const PLATFORM_ROOT = process.env.PLATFORM_ROOT;
if (!ACCOUNT_ID)
    throw new Error("ACCOUNT_ID environment variable is required");
if (!PLATFORM_ROOT)
    throw new Error("PLATFORM_ROOT environment variable is required");
const server = new McpServer({
    name: "replicate",
    version: "0.1.0",
});
// ---------------------------------------------------------------------------
// replicate-key-store — validate and persist a Replicate API token
// ---------------------------------------------------------------------------
// @ts-expect-error — MCP SDK server.tool() type inference exceeds depth limit with Zod v4
server.tool("replicate-key-store", "Validate and store a Replicate API token. Token must start with r8_.", {
    token: z.string().describe("Replicate API token (starts with r8_)"),
}, async ({ token }) => {
    // Format check
    if (!token.startsWith("r8_")) {
        return {
            content: [{ type: "text", text: "Invalid token format — must start with r8_." }],
            isError: true,
        };
    }
    // Validate against API
    const validation = await validateToken(token);
    if (validation.status === "auth_error") {
        return {
            content: [{ type: "text", text: "Token was rejected by Replicate — it may be invalid or revoked." }],
            isError: true,
        };
    }
    if (validation.status === "error") {
        return {
            content: [{ type: "text", text: `Could not validate token: ${validation.error ?? "unknown error"}` }],
            isError: true,
        };
    }
    // Persist
    try {
        writeToken(token);
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        return {
            content: [{ type: "text", text: `Token is valid but could not be saved: ${msg}` }],
            isError: true,
        };
    }
    return {
        content: [{ type: "text", text: `Replicate API token validated and stored (${validation.latencyMs}ms).` }],
    };
});
// ---------------------------------------------------------------------------
// replicate-key-verify — check stored token validity
// ---------------------------------------------------------------------------
server.tool("replicate-key-verify", "Read the stored Replicate API token and verify it against the Replicate API.", {}, async () => {
    const tokenResult = readToken();
    if (!tokenResult) {
        return {
            content: [{ type: "text", text: "No Replicate API token found. Source: none." }],
        };
    }
    const validation = await validateToken(tokenResult.token);
    return {
        content: [{
                type: "text",
                text: [
                    `Token source: ${tokenResult.source}`,
                    `Status: ${validation.status}`,
                    `Latency: ${validation.latencyMs}ms`,
                    ...(validation.error ? [`Error: ${validation.error}`] : []),
                ].join("\n"),
            }],
    };
});
// ---------------------------------------------------------------------------
// image-generate — generate images from text prompts
// ---------------------------------------------------------------------------
// @ts-expect-error — MCP SDK server.tool() type inference exceeds depth limit with Zod v4
server.tool("image-generate", [
    "Generate an image from a text prompt. Choose a model based on the content:",
    "- nano-banana-pro: photorealistic images, data-driven visuals, multilingual text rendering (94% legibility). Best for infographics, charts with labels, photo-quality illustrations. ~$0.04/image.",
    "- recraft-v4: design-quality compositions with intentional lighting, colour, and typography. Best for branded assets, print-ready artifacts, diagrams. Supports SVG output. ~$0.04/image.",
    "- flux-schnell: fast drafts for iteration and low-stakes production. Best for quick concept sketches and placeholder images. ~$0.003/image.",
].join("\n"), {
    prompt: z.string().describe("What to generate — content, composition, and any text to render"),
    model: z.enum(["nano-banana-pro", "recraft-v4", "flux-schnell"]).describe("nano-banana-pro (photorealistic, text rendering), recraft-v4 (design, branded, SVG), flux-schnell (fast drafts)"),
    aspectRatio: z.enum(["1:1", "4:3", "3:2", "16:9", "9:16"]).optional().describe("Image aspect ratio (default: 1:1)"),
    outputFormat: z.enum(["png", "webp", "svg"]).optional().describe("Output format (default: png, svg only with recraft-v4)"),
}, async ({ prompt, model, aspectRatio, outputFormat }) => {
    return imageGenerate({ prompt, model, aspectRatio: aspectRatio ?? "1:1", outputFormat: outputFormat ?? "png" }, ACCOUNT_ID, PLATFORM_ROOT);
});
// ---------------------------------------------------------------------------
// Start server
// ---------------------------------------------------------------------------
const transport = new StdioServerTransport();
await server.connect(transport);
//# sourceMappingURL=index.js.map