Skip to main content
Glama

TokenHub AIGC Model — MCP Server

MCP Server для вызова возможностей генерации изображений платформы больших языковых моделей TokenHub через MCP(Model Context Protocol). Клиенты могут настроить TokenHub API Key в любом клиенте, поддерживающем MCP (WorkBuddy / Claude Desktop / Cursor / любые AI IDE), и напрямую вызывать интерфейсы «текст-в-изображение» и «изображение-в-изображение / редактирование изображений» на естественном языке.

В настоящее время встроена примерная модель: custom-model-og-v2 (модель генерации изображений семейства GPT, синхронный ответ).


Возможности

  • Два инструмента

    • tokenhub_generate_image: «текст-в-изображение»(POST /v1/wand/og-image/generation,синхронный ответ)

    • tokenhub_edit_image: «изображение-в-изображение» / редактирование изображений(POST /v1/wand/og-image/edits,синхронный ответ,поддержка 1–16 входных изображений、локальная перерисовка по маске)

  • Два режима передачи

    • stdio(по умолчанию):локальное подключение клиентов напрямую, нулевое развертывание

    • streamable-http:развертывание в виде удалённой конечной точки для удалённого подключения внешних клиентов/команд

  • Гибкая настройка:API Key、домен сайта и имя модели настраиваются через переменные окружения; при отдельном вызове можно переопределить домен/модель(переключение узла или модели без изменения конфигурации)


Related MCP server: Vertex AI Imagen MCP Server

Быстрый старт

Способ 1: stdio(локальное под People, рекомендуется начать с него)

Добавьте MCP Server командного типа в конфигурацию MCP-клиента:

Клиент

Место настройки

WorkBuddy

~/.workbuddy/mcp.json,затем «Управление коннекторами → Пользовательский коннектор → Доверять»

Claude Desktop

claude_desktop_config.json

Cursor

Settings → MCP → Add new MCP server

{
  "mcpServers": {
    "tokenhub": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "tokenhub-aigc-model"],
      "env": {
        "TOKENHUB_API_KEY": "你的 TokenHub API Key",
        "TOKENHUB_BASE_URL": "https://tokenhub.tencentmaas.com",
        "TOKENHUB_MODEL": "custom-model-og-v2"
      },
      "description": "TokenHub 生图 MCP"
    }
  }
}

После настройки можно общаться напрямую: «Нарисуй котёнка, танцующего в полосе бамбука, 2048x2048».

Способ 2: Streamable HTTP(удалённое развертывание)

{
  "mcpServers": {
    "tokenhub": {
      "url": "https://你的服务域名/mcp",
      "headers": { "x-mcp-auth-token": "部署时设置的 MCP_AUTH_TOKEN" }
    }
  }
}

Переменные списка

Переменная

Обязательность

Значение по умолчанию

Описание

TOKENHUB_API_KEY

Да(при вызове — ошибка)

—

API Key, полученный в консоли TokenHub — заголовок запроса Authorization: Bearer <key>

TOKENHUB_BASE_URL

Нет

https://tokenhub.tencentmaas.com

Домен узла(см. описание узлов ниже),без слэша в конце

TOKENHUB_MODEL

Нет

custom-model-og-v2

Имя модели по умолчанию, может быть переопределено при отдельных вызовахро

MCP_AUTH_TOKEN

Нет(рекоменд для HTTP)

—

Необязательная проверка в HTTP: после настройки запросы /mcpдолжны содержать заголовок x-mcp-auth-token

Домены узлов

TokenHub развернут по региональным узлам; клиенты разных узлов должны указывать соответствующий домен. По умолчанию используется внутренний узел (Гуанчжоу):

Узел

Домен(пример)

Внутренний узел · Гуанчжоу

https://tokenhub.tencentmaas.com(по умолчанию)

Другие узлы(внутренний Сингапур / международные узлы Гуанчжоу、Сингапур、западное побережье США и т.д.)

Обратитесь к коммерческим/техническим специалистам TokenHub за доменом, укажите его в TOKENHUB_BASE_URL или передавайте base_url в вызове


Описание параметров инструментов

tokenhub_generate_image(текст-в-изображение)

Параметра

Требование

Описание

prompt

Да

Текстовое описание, максимум 32000 символов

base_url / model

Нет

Переопределить домен/модель для запуска

size

Нет

Размер генерации ширина x высота, например 2048x2048. Ограничения: сторона ≤3840px、ширина и высота кратны 16、соотношение длинной и короткой сторон ≤3:1、общая площадь 655360~8294400

quality

Нет

auto / high / medium / low

n

Нет

生成数量1–10,по умолчанию 1

background

Нет

opaque / auto

output_format

Нет

png / jpeg

output_compression

Нет

Уровень сжатия JPEG 0–100(только для jpeg)

response_format

Нет

url(по умолчанию)/ b64_json

tokenhub_edit_image(изображение-в-изображение/редактирование)

Использует параметры из предыдущего раздела,дополнительно Поддерживается:

Параметр

Только

Описание

input

Да

Входные изображения 1–16 шт.:[{ "image_url": "https://... 或 data:image/png;base64,..." }],png/jpg

mask

Нет

Маска для локальной перерисовки, размер должен совпадать с входным изображением

background

Нет

Дополнительно поддерживается transparent

Возвращается: скорость list URL изображений、request_id 来排查问题、total_tokens для учёта;при response_format=b64_jsonオ also возвращается блок base64 для прямого просмотра.


Обработка ошибок

  • При неуспешном вызове возвращается isError: true, в виз сообщении указывается status, code из вышестоящей ошибки и request_id。

  • При ошибках прав/лимитов/параметров сохраните request_id и передавайте его в техническую поддержку TokenHub для диагностики.

  • Если TOKENHUB_API_KEY не задан, вызов интерфуда бота возвращает понятное уведомление (нормально запускается)。


Вход HTTP(удалённо)

# 本地启动(默认 stdio)
npx -y tokenhub-aigc-model

# HTTP 模式
TOKENHUB_API_KEY=xxx MCP_AUTH_TOKEN=部署密钥 \
  npx -y tokenhub-aigc-model --transport=http --port=3000 --host=127.0.0.1

Endpoints:

  • POST /mcp、GET /mcp: входная точка протокола MCP

  • GET /health: проверка работоспособности

При выкладке в публиную сеть обязательно:

  1. Задайте MCP_AUTH_TOKEN or выполните отправку на предварительном шлюзе/в обратном прокси (например, EdgeOne、CLB、Nginx);

  2. Используйте HTTPS;

  3. base_url поддерживает переопределение при отдельном вызове; рекомендуется открывать только в доверенной средеокружение.


Разработка или публикация

npm install        # 安装依赖
npm run build      # TypeScript 构建到 dist/
npm test           # 单元测试 + stdio/HTTP 冒烟测试(共 20 个用例)
npm pack --dry-run # 查看发布内容

Опубликовать в npm Registry(если текущий registry является Новая Verteilung зеркалами, указываете явно):

npm run build
npm version patch
npm publish --access public --registry=https://registry.npmjs.org
git tag v0.1.0 && git push --tags

⚠️ Важные манипуляции

  1. Включение в список:custom-model-og-v2 — тестовая модель,для её использования необходимо отправить UIN и Appid в продукт/бэкенд TokenHub для открыты белый знак;бездействующие вызов вернет ошибку права доступа.

  2. API Key:создайте специальный key для соответствующеймодели Model in консоль TokenHub. Key показывается только фактически — хранить его надежени.

  3. Тарификация:TokenHub оплата по токенам(примерно 10 юаней за 1 млн токенов)——, периодическая детализация。n>1或 several входных图像会让消耗 значительно резко, просьба коммерческому отделу своевременно запросить скидку client.

  4. Финансовая формула(юаньки):текстовый вход токен×3.35 + token×0.8375 кэш ле input + 图片 input×5.36 + 图片 кэш input×1.34 + выходная 图片×20.1 = программный токен消耗(коэффициент пеобразования опирается на курс валют текущий 6.7)。


Лицензия

Apache-2.0

Available Tools

2 tools
tokenhub_edit_imageTokenHub 图生图/图片编辑A

调用 TokenHub 接口,基于 1-16 张输入图 + 文本描述同步生成图片(模型默认 custom-model-og-v2,需开白)。支持局部重绘(mask)。输入图支持 URL 或 base64。返回图片 URL 列表、request_id 与 token 用量。

ParametersJSON Schema
NameRequiredDescriptionDefault
nNo生成图片数量 1-10,默认 1
maskNo局部重绘蒙版图,尺寸需与输入图一致
sizeNo生成尺寸 "宽x高",如 2048x2048。约束:单边≤3840px、宽高为 16 的倍数、长短边比≤3:1、总像素 655360~8294400
modelNo单次覆盖模型名。不传时用环境变量 TOKENHUB_MODEL(默认 custom-model-og-v2)
imagesYes输入图 1-16 张,支持 URL 或 base64
promptYes文本描述,最大 32000 字符
qualityNo画质,默认 auto
base_urlNo单次覆盖站点域名(如 https://tokenhub.tencentmaas.com)。不传时用环境变量 TOKENHUB_BASE_URL
backgroundNo图像背景透明度:transparent 透明 / opaque 不透明 / auto 自动判断,默认 auto
output_formatNo输出格式,默认 png
response_formatNo返回格式:url(图片地址)或 b64_json(base64 数据),默认 url
output_compressionNoJPEG 压缩级别 0-100,仅 output_format=jpeg 时生效

TDQS

A4.2/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It discloses the model default, whitelist requirement, mask support, URL/base64 input acceptance, and return fields. It does not mention error behavior, rate limits, or auth mechanics, but it covers the main operational characteristics well.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is compact, informative, and well-front-loaded. It covers the core operation, constraints, input formats, mask feature, and return payload in four sentences with no fluff or redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the 12-parameter schema and absence of an output schema, the description provides enough operational context: input requirements, image count range, model default and whitelist, mask support, and response contents. It falls short of 5 only because of missing explicit alternative-tool routing and access/auth context.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the baseline is 3. The description mentions mask, input images, model default, and input formats, but most of these details are already documented in the schema. It adds only high-level context like whitelist and return metadata, not substantial new parameter-level semantics.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the operation: calling TokenHub to generate an image from 1-16 input images plus a text prompt, with support for mask-based local repainting. It also specifies the output contents (image URL list, request_id, token usage), making the tool's purpose and scope unambiguous.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description gives clear contextual signals for when to use this tool: when existing images are provided as input and editing/repainting is needed. It doesn't explicitly exclude or name the alternative tokenhub_generate_image, so the routing guidance is implied rather than explicit.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

tokenhub_generate_imageTokenHub 文生图A

调用 TokenHub 接口,根据文本描述同步生成图片(模型默认 custom-model-og-v2,需在 TokenHub 控制台开白并配置专属 API Key)。返回图片 URL 列表、request_id 与 token 用量。

ParametersJSON Schema
NameRequiredDescriptionDefault
nNo生成图片数量 1-10,默认 1
sizeNo生成尺寸 "宽x高",如 2048x2048。约束:单边≤3840px、宽高为 16 的倍数、长短边比≤3:1、总像素 655360~8294400
modelNo单次覆盖模型名。不传时用环境变量 TOKENHUB_MODEL(默认 custom-model-og-v2)
promptYes文本描述,最大 32000 字符
qualityNo画质,默认 auto
base_urlNo单次覆盖站点域名(如 https://tokenhub.tencentmaas.com)。不传时用环境变量 TOKENHUB_BASE_URL
backgroundNo图像背景透明度:opaque 不透明 / auto 自动判断,默认 auto
output_formatNo输出格式,默认 png
response_formatNo返回格式:url(图片地址)或 b64_json(base64 数据),默认 url
output_compressionNoJPEG 压缩级别 0-100,仅 output_format=jpeg 时生效

TDQS

A3.8/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It discloses that the call is synchronous, requires the user to have whitelisted the model and configured a dedicated API key, and that the response includes image URLs, request_id, and token usage. It does not cover error behavior or rate limits, but the key behavioral constraints are present.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two short, information-dense sentences with no redundancy. It ends with the action and auth prerequisite, then return values. Every word contributes to the agent's understanding.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with 10 parameters and no output schema, the description covers the important context: synchronous, auth required, default model, return shape. The schema covers parameter details, and what is missing (timeouts, error behavior) is minor for most use cases.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema documents all 10 parameters with detailed per-parameter descriptions, so the description adds very little for parameters. Mentioning the default model is useful but overlaps with the schema's model field. This is the expected baseline since schema coverage is 100%.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's action: calling TokenHub to synchronously generate an image from a text description, and identifies the resource (image). It does not explicitly contrast with tokenhub_edit_image, but the 'generate from text' wording is distinct enough.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies the appropriate scenario (generate an image from a prompt) and provides essential prerequisites (whitelist + dedicated API key). However, it gives no explicit guidance on when to prefer this over tokenhub_edit_image or when not to use it.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 2 tool updatesv0.1.0
    • First observedtokenhub_edit_image
    • First observedtokenhub_generate_image

TDQS

A4.1/5.0

Scored across 2 tools

Disambiguation5/5

The two tools have clearly distinct purposes: one generates an image purely from text, while the other edits/generates from 1-16 input images with optional masking. There is no realistic confusion between them.

Naming Consistency5/5

Both tools follow the same tokenhub_<verb>_image pattern with static verb prefixes: edit and generate. The naming convention is consistent and predictable.

Tool Count4/5

With only two tools, the server is slightly thin, but each tool covers a distinct core task in the image-generation domain. The focused scope makes the small count reasonable.

Completeness4/5

The two primary workflows—text-to-image generation and image editing/reinpainting—are covered, and the synchronous design avoids needing result-status tools. A minor gap is the lack of model-list or capability-discovery tooling, but agents can still complete the core tasks.

Maintenance

ActivitySlowing
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers