惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
G
Google Developers Blog
Blog — PlanetScale
Blog — PlanetScale
U
Unit 42
A
About on SuperTechFans
Vercel News
Vercel News
B
Blog
Martin Fowler
Martin Fowler
MyScale Blog
MyScale Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
腾讯CDC
D
Docker
V
Visual Studio Blog
博客园 - 叶小钗
The Cloudflare Blog
Jina AI
Jina AI
B
Blog RSS Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
WordPress大学
WordPress大学
T
Tailwind CSS Blog
MongoDB | Blog
MongoDB | Blog
D
DataBreaches.Net
月光博客
月光博客
大猫的无限游戏
大猫的无限游戏

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
i added MCP support to my SaaS in an afternoon. here's th...
Jill Mercer · 2026-05-25 · via DEV Community

I built Imagcon because I kept needing it. PWA icon generator — describe what you want, get all 19 sizes back plus splash screens and a manifest.json. every app I ship needs a fresh icon set and I got tired of doing it manually.
a few weeks ago I'm in the terminal with Claude Code working on something, I need icons, and I'm about to open a browser tab to do it. which means: describe the icon, wait for it to render, download the ZIP, drag the files into the project. while I'm already in a session where I could just say what I want.
so I asked Claude: is there a way to make this callable from inside the terminal, without leaving the editor?
MCP came back as the answer. I said let's build it. we went back and forth for an afternoon, hit one URL gotcha that cost me a solid hour, and by the end it was packaged and installable with one command. this is that whole afternoon.

what MCP is
Claude explained it to me as: you expose a set of functions, give them names and descriptions, and the AI can call them the same way it calls any built-in tool. the user never has to leave their editor.
before: "generate icons for my app" → switch tabs, describe, wait, download ZIP, drag files in.
after:
generate_pwa_icons("minimal blue compass on dark gradient", "./public/icons")

Claude Code runs that, extracts the ZIP, the icons land in your project. you keep typing.
(I've also been sitting on something that fits alongside this — a way to tell agents how to actually navigate your app, not just call the API. got deep into that before I even knew MCP existed. different post.)

the structure
three files. Claude laid this out before writing anything:
imagcon_mcp/
client.py # httpx wrapper around the Imagcon REST API
server.py # FastMCP tool definitions
main.py # entry point, auth, argparse

here's what's in each one.

the client
nothing clever — each method maps to one API call:
import io
import zipfile
from pathlib import Path
import httpx

BASE_URL = "https://imagcon.app"

class ImagconClient:
def init(self, api_key: str, timeout: float = 300.0) -> None:
self._client = httpx.Client(
base_url=BASE_URL,
headers={"Authorization": f"Bearer {api_key}"},
timeout=timeout,
)

def generate_image(self, description: str) -> dict:
    r = self._client.post(
        "/routes/generate-image",
        json={"description": description, "aspect_ratio": "1:1", "number_of_images": 1},
    )
    r.raise_for_status()
    return r.json()

def generate_pwa_icons(self, image_key: str) -> dict:
    r = self._client.post("/routes/generate-pwa-icons", json={"image_key": image_key})
    r.raise_for_status()
    return r.json()

@staticmethod
def extract_zip_to_dir(zip_bytes: bytes, output_dir: Path) -> None:
    output_dir.mkdir(parents=True, exist_ok=True)
    with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:
        zf.extractall(output_dir)

Enter fullscreen mode Exit fullscreen mode

the 300-second timeout — I found out why that matters the first time a request died mid-generation. image generation takes real compute time and the default httpx timeout cuts it off before it finishes. Claude bumped it after that happened.
the auth error handling was Claude thinking ahead:
def _request_error_message(self, response: httpx.Response) -> str:
if response.status_code in (401, 403):
return (
f"Imagcon API returned {response.status_code}. "
f"Check your API key at https://imagcon.app/api-keys"
)
return f"Imagcon API error {response.status_code}: {response.text[:500]}"

without something like this, a bad API key just returns a 401 with no useful message and you spend twenty minutes convinced it's a network problem.

the server
FastMCP makes this almost too simple. you decorate a function and it becomes a callable tool:
from mcp.server.fastmcp import FastMCP
from imagcon_mcp.client import ImagconClient

mcp = FastMCP("imagcon")
_client: ImagconClient | None = None

def set_client(client: ImagconClient) -> None:
global _client
_client = client

def _require_client() -> ImagconClient:
if _client is None:
raise RuntimeError("Imagcon client is not configured.")
return _client

I asked why the client was a global instead of passed around. Claude explained: the MCP server runs as a long-lived process, not a request handler — you wire up auth once at boot and reuse it across every tool call. hadn't thought about that. makes sense once you see it.
the main tool — the one that does the full pipeline:
@mcp.tool()
def generate_pwa_icons(description: str, output_dir: str = "./public/icons") -> str:
client = _require_client()
out = Path(output_dir)

# Step 1: generate the base image
gen = client.generate_image(description)
image_key = gen["image_key"]

# Step 2: resize to all 19 PWA sizes
pwa = client.generate_pwa_icons(image_key)
raw_icons = pwa["icons"]

# Step 3: save to gallery so it can be re-downloaded
save = client.save_pwa_icon_set(
    set_name=description[:99],
    original_image_key=image_key,
    icons=[{"size": ic["size"], "image_key": ic["image_key"]} for ic in raw_icons],
    prompt=description,
)

# Step 4: download the ZIP and extract
zip_bytes = client.download_pwa_icon_set_zip(save["set_id"])
ImagconClient.extract_zip_to_dir(zip_bytes, out)

return f"Generated {len(raw_icons)} icons in {out.resolve()}. manifest.json included."

Enter fullscreen mode Exit fullscreen mode

four API calls under the hood, but from the AI's perspective it's one tool with two parameters. it doesn't need to know about image keys or set IDs — those are just plumbing. the user says what they want, the tool handles everything.
the smaller tools follow the same pattern:
@mcp.tool()
def get_credit_balance() -> str:
data = _require_client().get_credit_balance()
return f"You have {data['remaining_credits']} credits remaining."

@mcp.tool()
def list_saved_icon_sets() -> str:
data = _require_client().list_pwa_icon_sets()
sets = data.get("icon_sets", [])
if not sets:
return "No saved icon sets found."
return "\n".join(
f"{s['id']}: {s['set_name']} (created {s['created_at'][:10]})"
for s in sets
)

return strings, not JSON. the AI reads the return value and decides what to say to the user — plain text relays directly. JSON makes the AI summarize the JSON, which adds noise.

the entry point
I didn't know how auth was typically handled for something like this. Claude set up two patterns — environment variable and CLI flag:
import argparse, os, sys
from imagcon_mcp.client import ImagconClient
from imagcon_mcp.server import mcp, set_client

def resolve_api_key(cli_key: str | None) -> str:
key = (cli_key or os.environ.get("IMAGCON_API_KEY") or "").strip()
if not key:
print(
"Missing Imagcon API key. Set IMAGCON_API_KEY or pass --api-key.\n"
"Create a key at https://imagcon.app/api-keys",
file=sys.stderr,
)
raise SystemExit(2)
if not key.startswith("ic_live
"):
print("Invalid API key format. Keys start with ic_live_.", file=sys.stderr)
raise SystemExit(2)
return key

def main() -> None:
parser = argparse.ArgumentParser(prog="imagcon-mcp")
parser.add_argument("--api-key", default=None)
args, remaining = parser.parse_known_args()
sys.argv = [sys.argv[0], *remaining] # pass remaining args to FastMCP

api_key = _resolve_api_key(args.api_key)
client = ImagconClient(api_key)
set_client(client)
try:
    mcp.run()
finally:
    client.close()

Enter fullscreen mode Exit fullscreen mode

the parse_known_args trick — I wouldn't have known to do that. it lets you add your own flags without conflicting with whatever FastMCP wants to pass through. the finally: client.close() cleans up the connection pool on shutdown; skip it and you'll see warnings.

packaging
[project]
name = "imagcon-mcp"
version = "0.1.3"
requires-python = ">=3.11"
dependencies = [
"mcp>=1.0.0",
"httpx>=0.27.0",
]

[project.scripts]
imagcon-mcp = "imagcon_mcp.main:main"

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

the [project.scripts] entry is what makes uvx imagcon-mcp work. uvx creates an isolated environment, installs the package, runs the script. no pip install step, no virtualenv the user has to manage.

the gotcha that cost me an hour
my backend routes are auto-discovered from Python modules and mounted at a prefix. so image_generator/generate_image should be at /routes/image_generator/generate_image.
in production it's not. the actual paths are flat: /routes/generate-image. the prefixes only exist in the router config, not in the deployed URLs.
I spent an hour calling paths that 404'd because I assumed the URL structure matched the file structure. Claude was working from the same wrong assumption I'd given it — so it didn't catch it either. we were both confidently wrong.
open your browser's network tab before you write a single line of client code. look at the actual request URLs your app makes. don't trust your mental model, and don't assume the AI's is any better than yours.

what I'd do differently
first version had four separate tools — one per API step. generate_image, generate_pwa_icons, save_set, download_set. the AI used them correctly but every conversation filled up with intermediate steps the user didn't care about. nobody needs to see the image key. collapsing everything into one generate_pwa_icons call made it dramatically cleaner. if nobody would ever want to stop in the middle of your pipeline, it should be one tool.
the docstrings matter more than I expected. I left them vague at first and the AI kept asking clarifying questions that weren't necessary. the function docstring is how the AI decides whether to use a tool and when — vague means it guesses.
the JSON return thing I found out by watching the AI respond. it would get a JSON blob back and then narrate the JSON to the user. switching to plain text fixed it immediately.

if you vibe code your apps you probably already have some service you built that you're constantly switching tabs to use. this pattern works for any of them.
full source is in the Imagcon repo. keys at imagcon.app/api-keys — I use it on every app I ship.