Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

feat(search): add Z.AI Coding Plan Search via MCP protocol (#2238)

Andrew Munsell0caca472d483
diff --git a/open-sse/config/searchRegistry.ts b/open-sse/config/searchRegistry.ts
index 893f185aac..724d349525 100644
--- a/open-sse/config/searchRegistry.ts
+++ b/open-sse/config/searchRegistry.ts
@@ -202,6 +202,22 @@ export const SEARCH_PROVIDERS: Record<string, SearchProviderConfig> = {
timeoutMs: 10_000,
cacheTTLMs: 5 * 60 * 1000,
},
+
+ "zai-search": {
+ id: "zai-search",
+ name: "Z.AI Coding Plan Search",
+ baseUrl: "https://api.z.ai/api/mcp/web_search_prime/mcp",
+ method: "POST",
+ authType: "apikey",
+ authHeader: "bearer",
+ costPerQuery: 0,
+ freeMonthlyQuota: 0,
+ searchTypes: ["web"],
+ defaultMaxResults: 5,
+ maxMaxResults: 50,
+ timeoutMs: 10_000,
+ cacheTTLMs: 5 * 60 * 1000,
+ },
};
/**
@@ -211,6 +227,7 @@ export const SEARCH_PROVIDERS: Record<string, SearchProviderConfig> = {
export const SEARCH_CREDENTIAL_FALLBACKS: Record<string, string> = {
"perplexity-search": "perplexity",
"ollama-search": "ollama-cloud",
+ "zai-search": "zai",
};
/**
diff --git a/open-sse/handlers/responsesHandler.ts b/open-sse/handlers/responsesHandler.ts
index b82d88cb50..65d18e6d1e 100644
--- a/open-sse/handlers/responsesHandler.ts
+++ b/open-sse/handlers/responsesHandler.ts
@@ -70,13 +70,13 @@ export async function handleResponsesCore({
// Transform SSE stream to Responses API format (no logging in worker)
const transformStream = createResponsesApiTransformStream(null);
- const transformedBody = response.body
- .pipeThrough(transformStream)
- .pipeThrough(createSseHeartbeatTransform({
+ const transformedBody = response.body.pipeThrough(transformStream).pipeThrough(
+ createSseHeartbeatTransform({
signal,
intervalMs: SSE_HEARTBEAT_INTERVAL_MS,
shape: HEARTBEAT_SHAPES.OPENAI_RESPONSES_IN_PROGRESS,
- }));
+ })
+ );
return {
success: true,
diff --git a/open-sse/handlers/search.ts b/open-sse/handlers/search.ts
index 55b8e3a4f2..b86c22dcac 100644
--- a/open-sse/handlers/search.ts
+++ b/open-sse/handlers/search.ts
@@ -5,7 +5,7 @@ import { randomUUID } from "crypto";
* Handles POST /v1/search requests.
* Routes to 11 search providers with automatic failover:
* serper-search, brave-search, perplexity-search, exa-search, tavily-search,
- * google-pse-search, linkup-search, searchapi-search, youcom-search, searxng-search, ollama-search
+ * google-pse-search, linkup-search, searchapi-search, youcom-search, searxng-search, ollama-search, zai-search
*
* Request format:
* {
@@ -18,6 +18,10 @@ import { randomUUID } from "crypto";
import { getSearchProvider, type SearchProviderConfig } from "../config/searchRegistry.ts";
import { saveCallLog } from "@/lib/usageDb";
+import { safeOutboundFetch } from "@/shared/network/safeOutboundFetch";
+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
+import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
+import { z } from "zod";
// ── Types ────────────────────────────────────────────────────────────────
@@ -928,6 +932,243 @@ function normalizeOllamaResponse(
return { results, totalResults: results.length };
}
+// ── Z.AI Coding Plan Search MCP Execution ───────────────────────────
+
+// Schema for the Z.AI MCP web_search_prime tool result. Z.AI double-encodes
+// the results array as a JSON string inside the MCP text content, so we
+// safely unwrap it with a typed schema instead of `JSON.parse(parsed)`.
+const ZaiSearchItemSchema = z
+ .object({
+ title: z.string().optional(),
+ link: z.string().optional(),
+ content: z.string().optional(),
+ publish_date: z.string().optional(),
+ icon: z.string().optional(),
+ media: z.string().optional(),
+ })
+ .passthrough();
+
+type ZaiSearchItem = z.infer<typeof ZaiSearchItemSchema>;
+
+const ZaiSearchResultsSchema = z.array(ZaiSearchItemSchema);
+
+/**
+ * Unwrap the double-encoded JSON from a Z.AI MCP web_search_prime response.
+ *
+ * Quirk: the MCP server returns a text content block whose body is a JSON
+ * string. That JSON string, once parsed, is itself another JSON string
+ * containing the actual results array. We try a single parse first
+ * (in case the upstream behavior ever changes), then a nested parse.
+ * Both paths are validated through `ZaiSearchResultsSchema` so any shape
+ * regression upstream lands in our error path instead of corrupting results.
+ */
+function unwrapZaiContent(rawText: string): ZaiSearchItem[] | null {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(rawText);
+ } catch {
+ return null;
+ }
+
+ // Direct array path (defensive, in case Z.AI stops double-encoding).
+ const direct = ZaiSearchResultsSchema.safeParse(parsed);
+ if (direct.success) return direct.data;
+
+ // Documented Z.AI behavior: parsed is a JSON string of the results array.
+ if (typeof parsed !== "string") return null;
+ let inner: unknown;
+ try {
+ inner = JSON.parse(parsed);
+ } catch {
+ return null;
+ }
+ const validated = ZaiSearchResultsSchema.safeParse(inner);
+ return validated.success ? validated.data : null;
+}
+
+async function zaiSearchExecute(params: {
+ config: SearchProviderConfig;
+ query: string;
+ token: string;
+ params: SearchRequestParams;
+ signal?: AbortSignal;
+}): Promise<{ results: SearchResult[]; totalResults: number | null }> {
+ const baseUrl = resolveSearchBaseUrl(params.config, params.params);
+ const transport = new StreamableHTTPClientTransport(new URL(baseUrl), {
+ fetch: safeOutboundFetch,
+ requestInit: {
+ headers: {
+ Authorization: `Bearer ${params.token}`,
+ },
+ },
+ });
+
+ const client = new Client({ name: "omniroute-search", version: "1.0" }, { capabilities: {} });
+
+ const { signal } = params;
+
+ let abortHandler: (() => void) | undefined;
+ if (signal) {
+ if (signal.aborted) {
+ throw new DOMException("The operation was aborted", "AbortError");
+ }
+ abortHandler = () => {
+ client.close().catch(() => {});
+ };
+ signal.addEventListener("abort", abortHandler, { once: true });
+ }
+
+ try {
+ await client.connect(transport);
+
+ if (signal?.aborted) {
+ throw new DOMException("The operation was aborted", "AbortError");
+ }
+
+ const args: Record<string, unknown> = {
+ search_query: params.query,
+ };
+
+ const { includes } = parseDomainFilter(params.params.domainFilter);
+ if (includes.length > 0) {
+ args.search_domain_filter = includes.join(",");
+ }
+
+ const toolResult = await client.callTool({
+ name: "web_search_prime",
+ arguments: args,
+ });
+
+ const rawContent = Array.isArray(toolResult.content) ? toolResult.content : [];
+ const rawText = rawContent
+ .filter((c: any) => c?.type === "text")
+ .map((c: any) => (typeof c?.text === "string" ? c.text : ""))
+ .join("\n");
+
+ if (!rawText.trim()) {
+ return { results: [], totalResults: null };
+ }
+
+ const items = unwrapZaiContent(rawText);
+ if (!items) {
+ return { results: [], totalResults: null };
+ }
+
+ const now = new Date().toISOString();
+ const results = items.map((item, idx) =>
+ makeResult(
+ "zai-search",
+ {
+ title: item.title,
+ url: item.link,
+ snippet: item.content || "",
+ published_at: item.publish_date,
+ favicon_url: item.icon,
+ source_type: item.media,
+ },
+ idx,
+ now
+ )
+ );
+ return { results, totalResults: results.length };
+ } finally {
+ if (abortHandler && signal) {
+ signal.removeEventListener("abort", abortHandler);
+ }
+ await client.close();
+ }
+}
+
+async function tryZaiMCPProvider(
+ config: SearchProviderConfig,
+ params: Omit<SearchRequestParams, "token">,
+ token: string,
+ providerSpecificData: Record<string, unknown> | undefined,
+ startTime: number,
+ globalStartTime: number,
+ log?: any
+): Promise<SearchHandlerResult> {
+ const { query, searchType, maxResults } = params;
+
+ const remainingGlobal = GLOBAL_TIMEOUT_MS - (Date.now() - globalStartTime);
+ const timeout = Math.min(config.timeoutMs, Math.max(remainingGlobal, 1000));
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeout);
+
+ try {
+ const normalized = await zaiSearchExecute({
+ config,
+ query,
+ token,
+ params: { ...params, token, providerSpecificData },
+ signal: controller.signal,
+ });
+ clearTimeout(timer);
+
+ const results = normalized.results.slice(0, maxResults);
+ const duration = Date.now() - startTime;
+
+ saveCallLog({
+ method: config.method,
+ path: "/v1/search",
+ status: 200,
+ model: config.id,
+ provider: config.id,
+ duration,
+ requestType: "search",
+ tokens: { prompt_tokens: 0, completion_tokens: 0 },
+ requestBody: { query: query.slice(0, 200), search_type: searchType, max_results: maxResults },
+ responseBody: { results_count: results.length, cached: false },
+ }).catch(() => {
+ /* non-critical — logging must not block search response */
+ });
+
+ return {
+ success: true,
+ data: {
+ provider: config.id,
+ query,
+ results,
+ answer: null,
+ usage: { queries_used: 1, search_cost_usd: config.costPerQuery },
+ metrics: {
+ response_time_ms: duration,
+ upstream_latency_ms: duration,
+ total_results_available: normalized.totalResults,
+ },
+ errors: [],
+ },
+ };
+ } catch (err: any) {
+ clearTimeout(timer);
+
+ const isTimeout = err.name === "AbortError";
+ if (log) {
+ log.error("SEARCH", `${config.id} MCP ${isTimeout ? "timeout" : "error"}: ${err.message}`);
+ }
+
+ saveCallLog({
+ method: config.method,
+ path: "/v1/search",
+ status: isTimeout ? 504 : 502,
+ model: config.id,
+ provider: config.id,
+ duration: Date.now() - startTime,
+ requestType: "search",
+ error: err.message,
+ requestBody: { query: query.slice(0, 200), search_type: searchType, max_results: maxResults },
+ }).catch(() => {
+ /* non-critical — logging must not block search response */
+ });
+
+ return {
+ success: false,
+ status: isTimeout ? 504 : 502,
+ error: `Search provider ${isTimeout ? "timeout" : "error"}: ${err.message}`,
+ };
+ }
+}
+
function normalizeResponse(
providerId: string,
data: any,
@@ -1060,6 +1301,19 @@ async function tryProvider(
}
const { query, searchType, maxResults } = params;
+
+ if (config.id === "zai-search" && token) {
+ return tryZaiMCPProvider(
+ config,
+ params,
+ token,
+ providerSpecificData,
+ startTime,
+ globalStartTime,
+ log
+ );
+ }
+
let url = "";
let init: RequestInit = {};
try {
diff --git a/open-sse/utils/sseHeartbeat.ts b/open-sse/utils/sseHeartbeat.ts
index 2c8d85a4c0..f0ef75a26f 100644
--- a/open-sse/utils/sseHeartbeat.ts
+++ b/open-sse/utils/sseHeartbeat.ts
@@ -12,7 +12,7 @@ export type HeartbeatShape = (typeof HEARTBEAT_SHAPES)[keyof typeof HEARTBEAT_SH
export const DEFAULT_SSE_HEARTBEAT_SHAPE: HeartbeatShape = HEARTBEAT_SHAPES.COMMENT;
export function shapeForClientFormat(
- clientResponseFormat: string | undefined | null,
+ clientResponseFormat: string | undefined | null
): HeartbeatShape {
switch (clientResponseFormat) {
case "claude":
@@ -28,7 +28,7 @@ export function shapeForClientFormat(
function buildHeartbeatPayload(
shape: HeartbeatShape,
- opts: { chunkId?: string; chunkModel?: string } = {},
+ opts: { chunkId?: string; chunkModel?: string } = {}
): string {
switch (shape) {
case HEARTBEAT_SHAPES.ANTHROPIC_PING:
@@ -90,7 +90,7 @@ export function createSseHeartbeatTransform({
try {
controller.enqueue(
- HEARTBEAT_ENCODER.encode(buildHeartbeatPayload(shape, { chunkId, chunkModel })),
+ HEARTBEAT_ENCODER.encode(buildHeartbeatPayload(shape, { chunkId, chunkModel }))
);
} catch {
stop();
diff --git a/src/lib/providers/validation.ts b/src/lib/providers/validation.ts
index 55a6b7763c..f101448701 100644
--- a/src/lib/providers/validation.ts
+++ b/src/lib/providers/validation.ts
@@ -2416,6 +2416,25 @@ const SEARCH_VALIDATOR_CONFIGS: Record<
body: JSON.stringify({ query: "test", max_results: 1 }),
},
}),
+ "zai-search": (apiKey, providerSpecificData = {}) => {
+ const baseUrl =
+ typeof providerSpecificData?.baseUrl === "string" && providerSpecificData.baseUrl.trim()
+ ? providerSpecificData.baseUrl.trim().replace(/\/+$/, "")
+ : "https://api.z.ai/api/mcp/web_search_prime/mcp";
+ return {
+ url: baseUrl,
+ init: {
+ method: "POST",
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` },
+ body: JSON.stringify({
+ jsonrpc: "2.0",
+ method: "tools/call",
+ params: { name: "web_search_prime", arguments: { search_query: "test" } },
+ id: 1,
+ }),
+ },
+ };
+ },
};
// See open-sse/executors/muse-spark-web.ts for the rationale: Meta migrated
diff --git a/src/shared/constants/providers.ts b/src/shared/constants/providers.ts
index 81776cbb52..dd7bd785a7 100644
--- a/src/shared/constants/providers.ts
+++ b/src/shared/constants/providers.ts
@@ -1798,6 +1798,16 @@ export const SEARCH_PROVIDERS = {
website: "https://ollama.com/settings/api-keys",
authHint: "Same API key as Ollama Cloud (from ollama.com/settings/api-keys)",
},
+ "zai-search": {
+ id: "zai-search",
+ alias: "zai-search",
+ name: "Z.AI Coding Plan Search",
+ icon: "search",
+ color: "#2563EB",
+ textIcon: "ZS",
+ website: "https://docs.z.ai/devpack/mcp/search-mcp-server",
+ authHint: "Same API key as Z.AI Coding Plan (from open.bigmodel.cn or z.ai)",
+ },
};
// Audio Only Providers
diff --git a/src/shared/validation/schemas.ts b/src/shared/validation/schemas.ts
index a8e471f917..2939886594 100644
--- a/src/shared/validation/schemas.ts
+++ b/src/shared/validation/schemas.ts
@@ -1805,6 +1805,7 @@ export const v1SearchSchema = z
"searchapi-search",
"youcom-search",
"searxng-search",
+ "zai-search",
])
.optional(),
max_results: z.coerce.number().int().min(1).max(100).default(5),
diff --git a/tests/unit/runtime-timeouts.test.ts b/tests/unit/runtime-timeouts.test.ts
index 5ec5b77df9..ec7927fe79 100644
--- a/tests/unit/runtime-timeouts.test.ts
+++ b/tests/unit/runtime-timeouts.test.ts
@@ -108,11 +108,13 @@ test("heartbeat interval default = 15s, env-overridable", () => {
assert.equal(runtimeTimeouts.DEFAULT_SSE_HEARTBEAT_INTERVAL_MS, 15_000);
assert.equal(runtimeTimeouts.getUpstreamTimeoutConfig({}).sseHeartbeatIntervalMs, 15_000);
assert.equal(
- runtimeTimeouts.getUpstreamTimeoutConfig({ SSE_HEARTBEAT_INTERVAL_MS: "8000" }).sseHeartbeatIntervalMs,
+ runtimeTimeouts.getUpstreamTimeoutConfig({ SSE_HEARTBEAT_INTERVAL_MS: "8000" })
+ .sseHeartbeatIntervalMs,
8_000
);
assert.equal(
- runtimeTimeouts.getUpstreamTimeoutConfig({ SSE_HEARTBEAT_INTERVAL_MS: "0" }).sseHeartbeatIntervalMs,
+ runtimeTimeouts.getUpstreamTimeoutConfig({ SSE_HEARTBEAT_INTERVAL_MS: "0" })
+ .sseHeartbeatIntervalMs,
0
);
});
diff --git a/tests/unit/search-handler-extended.test.ts b/tests/unit/search-handler-extended.test.ts
index cab4159653..5a0e206a44 100644
--- a/tests/unit/search-handler-extended.test.ts
+++ b/tests/unit/search-handler-extended.test.ts
@@ -868,3 +868,256 @@ test("handleSearch handles Ollama response with missing results field", async ()
globalThis.fetch = originalFetch;
}
});
+
+// ─── Z.AI Coding Plan Search Tests ────────────────────
+
+const ZAI_MOCK_RESULTS = [
+ {
+ title: "Z.AI Coding Plan Search",
+ link: "https://docs.z.ai/search",
+ content: "Z.AI now supports web search capabilities via Coding Plan",
+ publish_date: "2026-04-20T10:00:00Z",
+ icon: "https://docs.z.ai/favicon.ico",
+ media: "web",
+ },
+ {
+ title: "Getting Started with Z.AI",
+ link: "https://docs.z.ai/getting-started",
+ content: "Learn how to use Z.AI for search and inference",
+ publish_date: "2026-04-18T08:00:00Z",
+ icon: "https://docs.z.ai/favicon.ico",
+ media: "web",
+ },
+];
+
+test("handleSearch searches with Z.AI Coding Plan via MCP", async () => {
+ const originalFetch = globalThis.fetch;
+ const calls: { url: string; init: RequestInit }[] = [];
+ let capturedArgs: Record<string, unknown> = {};
+
+ globalThis.fetch = async (url, init = {}) => {
+ calls.push({ url: String(url), init });
+ const body = init.body ? JSON.parse(String(init.body)) : {};
+
+ // MCP initialize handshake
+ if (body.method === "initialize") {
+ return new Response(
+ JSON.stringify({
+ jsonrpc: "2.0",
+ result: {
+ protocolVersion: "2024-11-05",
+ capabilities: {},
+ serverInfo: { name: "zai-mcp", version: "1.0" },
+ },
+ id: body.id,
+ }),
+ {
+ status: 200,
+ headers: { "content-type": "application/json", "mcp-session-id": "session-abc-123" },
+ }
+ );
+ }
+
+ // notifications/initialized
+ if (body.method === "notifications/initialized") {
+ return new Response(null, { status: 202 });
+ }
+
+ // tools/call
+ if (body.method === "tools/call") {
+ capturedArgs = body.params.arguments;
+ return new Response(
+ JSON.stringify({
+ jsonrpc: "2.0",
+ result: {
+ content: [{ type: "text", text: JSON.stringify(JSON.stringify(ZAI_MOCK_RESULTS)) }],
+ },
+ id: body.id,
+ }),
+ { status: 200, headers: { "content-type": "application/json" } }
+ );
+ }
+
+ // GET (initial probe / transport check)
+ return new Response(null, { status: 405 });
+ };
+
+ try {
+ const result = await handleSearch({
+ query: "zai mcp search",
+ provider: "zai-search",
+ maxResults: 2,
+ searchType: "web",
+ credentials: { apiKey: "zai-token-abc" },
+ log: null,
+ });
+
+ assert.equal(result.success, true);
+ assert.equal(capturedArgs.search_query, "zai mcp search");
+ assert.equal(result.data.provider, "zai-search");
+ assert.equal(result.data.results.length, 2);
+ assert.equal(result.data.results[0].title, "Z.AI Coding Plan Search");
+ assert.equal(result.data.results[0].url, "https://docs.z.ai/search");
+ assert.equal(
+ result.data.results[0].snippet,
+ "Z.AI now supports web search capabilities via Coding Plan"
+ );
+ assert.equal(result.data.results[0].display_url, "docs.z.ai/search");
+ assert.equal(result.data.results[0].favicon_url, "https://docs.z.ai/favicon.ico");
+ assert.equal(result.data.results[0].citation.provider, "zai-search");
+ assert.equal(result.data.results[1].title, "Getting Started with Z.AI");
+ assert.equal(result.data.results[1].citation.provider, "zai-search");
+ assert.equal(result.data.usage.queries_used, 1);
+ assert.equal(result.data.usage.search_cost_usd, 0);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
+test("handleSearch handles Z.AI Coding Plan empty MCP results", async () => {
+ const originalFetch = globalThis.fetch;
+
+ globalThis.fetch = async (url, init = {}) => {
+ const body = init.body ? JSON.parse(String(init.body)) : {};
+
+ if (body.method === "initialize") {
+ return new Response(
+ JSON.stringify({
+ jsonrpc: "2.0",
+ result: {
+ protocolVersion: "2024-11-05",
+ capabilities: {},
+ serverInfo: { name: "zai-mcp", version: "1.0" },
+ },
+ id: body.id,
+ }),
+ {
+ status: 200,
+ headers: { "content-type": "application/json", "mcp-session-id": "session-empty" },
+ }
+ );
+ }
+
+ if (body.method === "notifications/initialized") {
+ return new Response(null, { status: 202 });
+ }
+
+ if (body.method === "tools/call") {
+ return new Response(
+ JSON.stringify({
+ jsonrpc: "2.0",
+ result: {
+ content: [{ type: "text", text: JSON.stringify(JSON.stringify([])) }],
+ },
+ id: body.id,
+ }),
+ { status: 200, headers: { "content-type": "application/json" } }
+ );
+ }
+
+ return new Response(null, { status: 405 });
+ };
+
+ try {
+ const result = await handleSearch({
+ query: "empty zai mcp result",
+ provider: "zai-search",
+ maxResults: 5,
+ searchType: "web",
+ credentials: { apiKey: "zai-key" },
+ log: null,
+ });
+
+ assert.equal(result.success, true);
+ assert.equal(result.data.provider, "zai-search");
+ assert.equal(result.data.results.length, 0);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
+test("handleSearch handles Z.AI Coding Plan MCP connection error", async () => {
+ const originalFetch = globalThis.fetch;
+
+ globalThis.fetch = async () => {
+ throw new Error("Connection refused");
+ };
+
+ try {
+ const result = await handleSearch({
+ query: "zai mcp error",
+ provider: "zai-search",
+ maxResults: 5,
+ searchType: "web",
+ credentials: { apiKey: "zai-key" },
+ log: null,
+ });
+
+ assert.equal(result.success, false);
+ assert.equal(result.status, 502);
+ assert.ok(result.error.includes("error"));
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
+test("handleSearch handles Z.AI Coding Plan non-array MCP result", async () => {
+ const originalFetch = globalThis.fetch;
+
+ globalThis.fetch = async (url, init = {}) => {
+ const body = init.body ? JSON.parse(String(init.body)) : {};
+
+ if (body.method === "initialize") {
+ return new Response(
+ JSON.stringify({
+ jsonrpc: "2.0",
+ result: {
+ protocolVersion: "2024-11-05",
+ capabilities: {},
+ serverInfo: { name: "zai-mcp", version: "1.0" },
+ },
+ id: body.id,
+ }),
+ {
+ status: 200,
+ headers: { "content-type": "application/json", "mcp-session-id": "session-nonarray" },
+ }
+ );
+ }
+
+ if (body.method === "notifications/initialized") {
+ return new Response(null, { status: 202 });
+ }
+
+ if (body.method === "tools/call") {
+ return new Response(
+ JSON.stringify({
+ jsonrpc: "2.0",
+ result: {
+ content: [{ type: "text", text: JSON.stringify(JSON.stringify({ not: "an array" })) }],
+ },
+ id: body.id,
+ }),
+ { status: 200, headers: { "content-type": "application/json" } }
+ );
+ }
+
+ return new Response(null, { status: 405 });
+ };
+
+ try {
+ const result = await handleSearch({
+ query: "zai non-array",
+ provider: "zai-search",
+ maxResults: 5,
+ searchType: "web",
+ credentials: { apiKey: "zai-key" },
+ log: null,
+ });
+
+ assert.equal(result.success, true);
+ assert.equal(result.data.results.length, 0);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
diff --git a/tests/unit/search-registry.test.ts b/tests/unit/search-registry.test.ts
index f7900d1f52..01bd1adc88 100644
--- a/tests/unit/search-registry.test.ts
+++ b/tests/unit/search-registry.test.ts
@@ -19,7 +19,7 @@ const { computeCacheKey, getOrCoalesce, getCacheStats, SEARCH_CACHE_DEFAULT_TTL_
// ─── Registry Tests ──────────────────────────────────────────
-test("SEARCH_PROVIDERS has all 10 providers", () => {
+test("SEARCH_PROVIDERS has all 11 providers", () => {
assert.ok(SEARCH_PROVIDERS["serper-search"], "serper should exist");
assert.ok(SEARCH_PROVIDERS["brave-search"], "brave should exist");
assert.ok(SEARCH_PROVIDERS["perplexity-search"], "perplexity-search should exist");
@@ -31,7 +31,8 @@ test("SEARCH_PROVIDERS has all 10 providers", () => {
assert.ok(SEARCH_PROVIDERS["youcom-search"], "youcom should exist");
assert.ok(SEARCH_PROVIDERS["searxng-search"], "searxng should exist");
assert.ok(SEARCH_PROVIDERS["ollama-search"], "ollama-search should exist");
- assert.equal(Object.keys(SEARCH_PROVIDERS).length, 11);
+ assert.ok(SEARCH_PROVIDERS["zai-search"], "zai should exist");
+ assert.equal(Object.keys(SEARCH_PROVIDERS).length, 12);
});
test("serper-search config is correct", () => {
@@ -140,6 +141,17 @@ test("searxng-search config is correct", () => {
assert.deepEqual(s.searchTypes, ["web", "news"]);
});
+test("zai-search config is correct", () => {
+ const z = SEARCH_PROVIDERS["zai-search"];
+ assert.equal(z.id, "zai-search");
+ assert.equal(z.method, "POST");
+ assert.equal(z.authHeader, "bearer");
+ assert.equal(z.baseUrl, "https://api.z.ai/api/mcp/web_search_prime/mcp");
+ assert.equal(z.costPerQuery, 0);
+ assert.equal(z.freeMonthlyQuota, 0);
+ assert.deepEqual(z.searchTypes, ["web"]);
+});
+
test("getAllSearchProviders returns flat list", () => {
const all = getAllSearchProviders();
assert.equal(all.length, 11);
@@ -154,6 +166,7 @@ test("getAllSearchProviders returns flat list", () => {
assert.ok(all.some((p) => p.id === "youcom-search"));
assert.ok(all.some((p) => p.id === "searxng-search"));
assert.ok(all.some((p) => p.id === "ollama-search"));
+ assert.ok(all.some((p) => p.id === "zai-search"));
// Each entry should have id, name, searchTypes
for (const p of all) {
assert.ok(p.id);
diff --git a/tests/unit/search-route.test.ts b/tests/unit/search-route.test.ts
index f948e072e8..08ba7c9598 100644
--- a/tests/unit/search-route.test.ts
+++ b/tests/unit/search-route.test.ts
@@ -45,14 +45,14 @@ test.after(() => {
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
});
-test("v1 search GET lists all 11 search providers", async () => {
+test("v1 search GET lists all 12 search providers", async () => {
const response = await searchRoute.GET();
const body = (await response.json()) as any;
const ids = body.data.map((item: { id: string }) => item.id);
assert.equal(response.status, 200);
assert.equal(body.object, "list");
- assert.equal(body.data.length, 11);
+ assert.equal(body.data.length, 12);
assert.deepEqual(ids, [
"serper-search",
"brave-search",
@@ -65,6 +65,7 @@ test("v1 search GET lists all 11 search providers", async () => {
"youcom-search",
"searxng-search",
"ollama-search",
+ "zai-search",
]);
});
diff --git a/tests/unit/sse-heartbeat-integration.test.ts b/tests/unit/sse-heartbeat-integration.test.ts
index 0b3a2764f4..9c36ec5f91 100644
--- a/tests/unit/sse-heartbeat-integration.test.ts
+++ b/tests/unit/sse-heartbeat-integration.test.ts
@@ -1,9 +1,8 @@
import test from "node:test";
import assert from "node:assert/strict";
-const { createSseHeartbeatTransform, HEARTBEAT_SHAPES, shapeForClientFormat } = await import(
- "../../open-sse/utils/sseHeartbeat.ts"
-);
+const { createSseHeartbeatTransform, HEARTBEAT_SHAPES, shapeForClientFormat } =
+ await import("../../open-sse/utils/sseHeartbeat.ts");
const STREAM_TS_STRIP_RE = /^event:\s*keepalive\b/i;
@@ -19,7 +18,9 @@ test("integration: anthropic-ping heartbeat reaches downstream and does NOT trig
controller.enqueue(new TextEncoder().encode("event: message_start\ndata: {}\n\n"));
// never close — let heartbeat fire
},
- cancel() { cancelled = true; },
+ cancel() {
+ cancelled = true;
+ },
});
const transform = createSseHeartbeatTransform({
@@ -61,7 +62,11 @@ test("integration: anthropic-ping heartbeat reaches downstream and does NOT trig
test("integration: openai-chunk heartbeat is valid JSON parseable by SDKs", async () => {
const upstream = new ReadableStream({
start(controller) {
- controller.enqueue(new TextEncoder().encode(`data: {"id":"chatcmpl-1","object":"chat.completion.chunk","choices":[]}\n\n`));
+ controller.enqueue(
+ new TextEncoder().encode(
+ `data: {"id":"chatcmpl-1","object":"chat.completion.chunk","choices":[]}\n\n`
+ )
+ );
},
});
diff --git a/tests/unit/sse-heartbeat.test.ts b/tests/unit/sse-heartbeat.test.ts
index be017470df..3700137adc 100644
--- a/tests/unit/sse-heartbeat.test.ts
+++ b/tests/unit/sse-heartbeat.test.ts
@@ -142,7 +142,10 @@ test("shape: openai-chunk emits valid chat.completion.chunk with empty delta", a
test("shape: openai-responses-in-progress emits response.in_progress data event", async () => {
await withFakeIntervals(async (intervals) => {
- const transform = createSseHeartbeatTransform({ intervalMs: 100, shape: "openai-responses-in-progress" });
+ const transform = createSseHeartbeatTransform({
+ intervalMs: 100,
+ shape: "openai-responses-in-progress",
+ });
const writer = transform.writable.getWriter();
const reader = transform.readable.getReader();
const emitted = [];
@@ -240,7 +243,11 @@ test("no shape collides with stream.ts event: keepalive strip regex", async () =
const lines = emitted[0].split("\n");
for (const line of lines) {
- assert.doesNotMatch(line.trim(), /^event:\s*keepalive\b/i, `shape ${shape} produced forbidden line: ${line}`);
+ assert.doesNotMatch(
+ line.trim(),
+ /^event:\s*keepalive\b/i,
+ `shape ${shape} produced forbidden line: ${line}`
+ );
}
});
}