Integrating AI Agents with ZenTao via MCP Server: Full Implementation Guide
This guide details building a secure MCP server in Node.js to connect AI agents with ZenTao bug tracking, covering token caching, HTTPS enforcement, path validation, multi-path bug list fallback, HTML parsing with image extraction, state transition tools, and local archiving via SKILL for persistent context.
Reading font

Overall Architecture
The system follows a three-tier architecture: Agent ↔ MCP Server ↔ ZenTao REST API. The MCP server (Node.js 18+) communicates with the AI agent via stdio (JSON-RPC) and with ZenTao via HTTPS using token-based authentication. A companion SKILL archives bug context locally under bugfix/<YYYY-MM-DD>/bug-<id>-<assignee>/.
Key Design Choices
Node.js 18+ : Uses built-in fetch and AbortController, eliminating external dependencies like node-fetch.
stdio transport : The MCP server does not listen on a network port, avoiding auth, CORS, and TLS complexity.
No secrets in repo : All credentials read from environment variables; default logs redact sensitive fields.
Minimal Viable Setup (5 Minutes)
Step 1: Prepare ZenTao Instance
Obtain and verify three items:
# 1. ZenTao base URL (must be HTTPS)
ZENTAO_BASE_URL="https://zentao.example.com"
# 2. Minimal-privilege service account (not admin)
ZENTAO_ACCOUNT="bot_account"
ZENTAO_PASSWORD="<from-vault>"
# 3. Verify token endpoint
curl -sS -X POST "$ZENTAO_BASE_URL/api.php/v1/tokens" \
-H 'Content-Type: application/json' \
-d "{\"account\":\"$ZENTAO_ACCOUNT\",\"password\":\"$ZENTAO_PASSWORD\"}"
# Expect { "token": "xxxxxxxxxxxxxxxx", ... }If no token field returns, confirm the API prefix is /api.php/v1 and RESTful API v1 is enabled.
Step 2: Project Skeleton
mkdir zentao-mcp-server && cd zentao-mcp-server
npm init -y
npm i @modelcontextprotocol/sdk
node -e "console.log(process.versions.node)" # must be >= 18
# package.json additions:
{
"type": "module",
"main": "src/index.js",
"scripts": { "start": "node src/index.js" },
"dependencies": { "@modelcontextprotocol/sdk": "^1.0.0" }
}Step 3: Minimal ZenTao Client with Token Caching
export function createZenTaoClient({ baseUrl, account, password }) {
let cachedToken = "";
let cachedAt = 0;
const TTL = 50 * 60 * 1000; // 50 minutes
async function getToken() {
if (cachedToken && Date.now() - cachedAt < TTL) return cachedToken;
const resp = await fetch(`${baseUrl}/api.php/v1/tokens`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ account, password }),
});
const data = await resp.json();
const token = data?.token || data?.data?.token;
if (!token) throw new Error("token field missing");
cachedToken = token;
cachedAt = Date.now();
return token;
}
async function call(path, { method = "GET", query, body } = {}) {
const token = await getToken();
const url = new URL(`${baseUrl}/api.php/v1${path}`);
if (query) for (const [k, v] of Object.entries(query)) {
if (v != null) url.searchParams.set(k, String(v));
}
const resp = await fetch(url, {
method,
headers: { Token: token, "Content-Type": "application/json" },
body: body ? JSON.stringify(body) : undefined,
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
return resp.json();
}
return { getToken, call };
}This skeleton omits timeout, path allow-list, and HTTPS enforcement — added later.
Step 4: Register First Tool ( get_my_bugs )
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
import { createZenTaoClient } from "./zentao.js";
const zentao = createZenTaoClient({
baseUrl: process.env.ZENTAO_BASE_URL.replace(//+$/, ""),
account: process.env.ZENTAO_ACCOUNT,
password: process.env.ZENTAO_PASSWORD,
});
const TOOLS = [{
name: "get_my_bugs",
description: "Get bugs assigned to current account",
inputSchema: {
type: "object",
properties: {
status: { type: "string", enum: ["active", "resolved", "closed"] },
limit: { type: "number", default: 20 },
},
},
}];
const server = new Server(
{ name: "zentao-mcp-server", version: "0.1.0" },
{ capabilities: { tools: {} } },
);
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
server.setRequestHandler(CallToolRequestSchema, async (req) => {
const { name, arguments: args = {} } = req.params;
if (name === "get_my_bugs") {
const data = await zentao.call("/bugs", {
query: { limit: args.limit ?? 20, status: args.status, assignedTo: process.env.ZENTAO_ACCOUNT },
});
return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
}
throw new Error(`Unknown tool: ${name}`);
});
await server.connect(new StdioServerTransport());Step 5: Connect to Claude Desktop / Cursor
Add to MCP client config:
{
"mcpServers": {
"zentao": {
"command": "node",
"args": ["/abs/path/to/zentao-mcp-server/src/index.js"],
"env": {
"ZENTAO_BASE_URL": "https://zentao.example.com",
"ZENTAO_ACCOUNT": "bot_account",
"ZENTAO_PASSWORD": "<from-vault>"
}
}
}
}Restart the client and ask the agent: "List my active bugs." If a list returns, the end-to-end path works.
Complete Tool Set (10 Tools)
Tools are grouped by responsibility. Design highlights:
Read/write naming : Action tools use verb-object (e.g., resolve_bug, close_bug) so the model instantly sees side effects.
Structured errors : Every tool returns { ok: false, tool, message, status, hint }; hint includes the most common fix (e.g., "Set ZENTAO_PRODUCT_ID when seeing Need product id").
Batch operations default to stopOnError=true : High-risk bulk changes halt on first error for manual review instead of silently continuing.
Security Hardening at Token & Request Layer
1. Enforce HTTPS
const parsed = new URL(baseUrl);
const allowInsecure = String(process.env.ZENTAO_ALLOW_INSECURE_HTTP) === "true";
if (parsed.protocol !== "https:" && !(allowInsecure && parsed.protocol === "http:")) {
throw new Error("baseUrl must use HTTPS unless ZENTAO_ALLOW_INSECURE_HTTP=true");
}2. Relative Path Allow-List
All dynamic paths validated to prevent SSRF:
function assertSafeRelativePath(value, field) {
const raw = String(value || "").trim();
if (!raw) throw new Error(`${field} is required`);
if (/^https?:\/\//i.test(raw)) throw new Error(`${field} must be relative`);
if (raw.startsWith("//")) throw new Error(`${field} must not be protocol-relative`);
const normalized = raw.startsWith("/") ? raw : `/${raw}`;
if (normalized.includes("?") || normalized.includes("#"))
throw new Error(`${field} must not include query or hash`);
const low = normalized.toLowerCase();
if (/(^|\/)\.{1,2}(?:\/|$)/.test(normalized) || low.includes("%2e"))
throw new Error(`${field} must not contain dot segments`);
return normalized;
}3. Request Timeout via AbortController
function createAbortSignal(timeoutMs) {
const controller = new AbortController();
const t = setTimeout(() => controller.abort(new Error("Request timeout")), timeoutMs);
return { signal: controller.signal, cleanup: () => clearTimeout(t) };
}4. Log Redaction
When ZENTAO_DEBUG=true, tool-call arguments are written to stderr with sensitive fields replaced:
const REDACTED = new Set(["body", "query", "comment", "solution", "password", "token"]);
function sanitize(args) {
const out = {};
for (const [k, v] of Object.entries(args || {})) {
out[k] = REDACTED.has(k) ? "<redacted>" : v;
}
return out;
}Fields like solution and comment are redacted because they often contain file paths, internal API names, or reproduction credentials.
Multi-Path Bug List Fallback
ZenTao deployments vary heavily; the same "assigned to me" bugs may live under three distinct endpoints:
Product view : /products/{productId}/bugs (needs ZENTAO_PRODUCT_ID)
Project-set/program view : /projectsets/{id}/bugs or /programs/{id}/projects/{pid}/bugs "My" view : /my/bug or /my/bugs (only endpoint that works on some instances)
Implementation uses a candidate-path list with sequential fallback and merge-dedupe:
const candidatePaths = [];
if (preferProjectSetPath) candidatePaths.push(...projectSetPaths);
candidatePaths.push(primaryPath);
if (effectiveProductId) candidatePaths.push(`/products/${effectiveProductId}/bugs`);
if (!preferProjectSetPath) candidatePaths.push(...projectSetPaths);
if (configuredMyBugsPath) candidatePaths.push(configuredMyBugsPath);
for (const fallback of fallbackPaths) candidatePaths.push(fallback);Each path is tried even if the previous returned an empty list; successful results are merged by bug ID. The response includes raw.triedPaths with HTTP status and hit count for debugging.
Two nuances:
"My bug" and "project-set bug" endpoints often ignore assignedTo / status / product query params, so the server only sends limit / page and filters locally. list_my_projects cannot be the sole source for project-set bugs because some project-sets have no child projects yet still hold bugs; the server directly hits the project-set bug endpoint when the ID is known.
Bug Detail Parsing & Image Archiving
get_bug_detailperforms five steps:
Calls fixed /bugs/{id} to prevent model-injected paths.
Crops response to safe fields via buildSafeBugDetail() (keeps title, status, severity, pri, openedBy, etc.) and normalizes assignedTo (sometimes object, sometimes string) through normalizeUserIdentity().
Preserves stepsHtml and commentHtml raw HTML because embedded <img src="...fileID=N"> tags are the source for screenshot extraction; plain text would lose them.
Extracts imageFileIds[] using two regexes:
const patterns = [/fileID=(\d+)/gi, /\/files\/(\d+)/gi];
function extractFileIds(html) {
const ids = new Set();
for (const re of patterns) {
for (const m of String(html || "").matchAll(re)) {
const n = Number(m[1]);
if (Number.isFinite(n) && n > 0) ids.add(n);
}
}
return [...ids];
}Same-origin URL allow-list: normalizeResourceUrl() only passes links sharing the ZENTAO_BASE_URL origin; external image hosts and third-party CDNs are stripped to avoid phishing links.
Images are fetched individually via get_bug_image({ fileId }). The server calls /api.php/v1/files/{id}, streams the binary, truncates at maxBytes (default 2 MB, hard cap 5 MB), returns base64 with a truncated: true flag so the client can request a larger maxBytes if needed.
State Transition Tools
Write operations are semantically simple but parameterized carefully: resolve_bug requires id, defaults resolution=fixed, encourages solution covering "root cause + fix approach + change logic + impact scope". Server builds the final comment via buildResolutionComment():
function buildResolutionComment({ solution, comment, resolution }) {
const s = String(solution || "").trim();
if (s) return `\u89e3\u51b3\u8bf4\u660e\uff1a${s}`;
const c = String(comment || "").trim();
if (c) return c;
return `\u5df2\u5904\u7406\uff0cresolution=${resolution || "fixed"}`;
}verify_bugmaps QA flow: result=pass → close, result=fail → activate. batch_resolve_my_bugs defaults maxItems=20, hard limit 100, stopOnError=true. Explicit solution required to avoid "batch fixed with empty description" traces. comment_bug falls back from /bugs/{id}/comment to /bugs/{id}/comments only on 404; other errors bubble up to prevent duplicate comments on 5xx retries.
Companion SKILL: Local Archiving
MCP tools alone lose context between sessions. The SKILL persists bug context to the local workspace.
Directory Constraints
<project-root>/
└── bugfix/
└── <YYYY-MM-DD>/ # today's date
└── bug-<id>-<assignee>/ # e.g., bug-1024-frontend_a
├── index.md # human-readable summary
├── raw.json # raw MCP response
└── images/ # all screenshots
└── file-12.pngConstraints in priority order:
Strict naming : bugfix/ (lowercase, singular) / <YYYY-MM-DD> / bug-<id>-<assignee>; assignee lowercased, non- [a-z0-9_-] replaced with _.
Only active bugs archived : List queries don't trigger; resolved/closed bugs skipped to avoid flooding archive with history.
Re-assignment creates new directory : bug-1024-frontend_a and bug-1024-frontend_b coexist, preserving handoff trail.
HTML → Markdown : <img src="...fileID=N"> rewritten to local ./images/file-N.png; other rich text stripped to plain text + Markdown.
bugfix/ in .gitignore : Contains internal screenshots; not committed. Share a specific bug's directory via IM when needed.
Enabling the SKILL in a Project
# 1. Create SKILL directory (Claude Code auto-loads)
mkdir -p .claude/skills/zentao-bugfix
touch .claude/skills/zentao-bugfix/SKILL.md
# 2. Add bugfix/ to .gitignore
echo -e "
# Zentao bug context (local fix drafts; may contain internal screenshots)
/bugfix/" >> .gitignore
# 3. In SKILL.md define trigger + directory constraints + index.md template
# (Trigger: user says "look at bug N / pull bug N / fix bug N", or agent calls get_bug_detail)The SKILL.md encodes the directory rules, the index.md template, and the action-field mapping table so every get_bug_detail call archives identically.
Production Safety Checklist
Before rolling out to the team, verify each item:
Use a least-privilege service account — only the needed products/project-sets, never an admin account. ZENTAO_BASE_URL must be HTTPS; ZENTAO_ALLOW_INSECURE_HTTP not enabled. .env never committed; use .env.example as placeholder, inject secrets from vault (1Password, Vault, etc.).
Credentials never enter agent context: MCP server holds token in process memory; token never echoed to the model.
Write operations limited to four semantic tools ( resolve, close, verify, comment); no generic POST passthrough.
Batch actions default stopOnError=true, maxItems ≤ 100.
All paths go through allow-list + relative-path validation; SSRF blocked.
Images filtered by same-origin allow-list + maxBytes truncation; external links dropped.
Logging off by default; ZENTAO_DEBUG=true redacts sensitive fields to <redacted>.
SKILL's bugfix/ directory in .gitignore to prevent accidental push of internal screenshots.
Summary
Integrating ZenTao with AI agents is not merely "letting the agent call ZenTao APIs"; it's about moving bug-process context from the ZenTao web UI into the agent's tool surface and a local working directory. Rollout in four phases:
Minimal MCP SDK version (5 minutes).
Token caching, path allow-list, HTTPS enforcement, log redaction (half day).
Multi-path bug list fallback + same-origin image cropping (1 day).
Companion archival SKILL (half day).
Most reusable decisions:
MCP as boundary : All ZenTao ops exposed via 10 explicit semantic tools; credentials stay out of context; write ops require explicit params.
Path polymorphism fallback : Don't assume one ZenTao shape; candidate paths + sequential fallback + merge-dedupe is the pragmatic adapter.
Preserve raw HTML structure : Plain text loses screenshots, but embedded URLs must pass same-origin allow-list.
SKILL turns ephemeral data into traceable archives : Bug context archived by date + assignee is far more reliable than expecting the agent to "remember".
As AI increasingly handles "read bug, locate code, write fix", the bug platform becomes one of the highest-value external systems to integrate early. A well-controlled MCP Server plus a strict archival SKILL is the minimum viable engineering solution for this step.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.