Skip to content
20 changes: 17 additions & 3 deletions packages/commands/src/commands/mcp/activate-hint.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { BailianError } from "bailian-cli-core";
import { BailianError, isStreamableHttpUnsupported } from "bailian-cli-core";
import { mcpMarketplaceDetailPage } from "bailian-cli-runtime";

/** Detect MCP-not-activated / invalid 404 errors (CLI-wrapped server message). */
export function isMcpNotActivated(error: unknown): boolean {
if (!(error instanceof BailianError)) return false;
const message = error.message;
if (!/MCP request failed:\s*404\b/i.test(message)) return false;
if (!/^MCP request failed:\s*404\b/i.test(message)) return false;
return /未开通|MCP不存在|MCP_IS_INVALID/i.test(message);
}

Expand All @@ -26,14 +26,28 @@ export function mcpActivateHint(serverCode: string): string {
/**
* For not-activated errors, keep the original message / exitCode and append a hint only.
* Do not replace the server error message.
* WebSearch + 405 streamableHttp: do not fall back; attach a re-activate / upgrade hint.
*/
export function rethrowWithMcpActivateHint(error: unknown, serverCode: string): never {
if (isMcpNotActivated(error) && error instanceof BailianError && !error.hint) {
if (!(error instanceof BailianError) || error.hint) {
throw error;
}

if (isMcpNotActivated(error)) {
throw new BailianError(error.message, error.exitCode, mcpActivateHint(serverCode), {
cause: error,
api: error.api,
rawResponse: error.rawResponse,
});
}

if (serverCode === "WebSearch" && isStreamableHttpUnsupported(error)) {
throw new BailianError(error.message, error.exitCode, mcpActivateHint(serverCode), {
cause: error,
api: error.api,
rawResponse: error.rawResponse,
});
}

throw error;
}
18 changes: 11 additions & 7 deletions packages/commands/src/commands/mcp/call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ const CALL_FLAGS = {
url: {
type: "string",
valueHint: "<url>",
description: "Override the MCP endpoint URL (for non-Bailian servers)",
description:
"Override the MCP endpoint URL (non-Bailian). Tries Streamable HTTP first, then classic SSE on the same URL.",
},
} satisfies FlagsDef;
type CallFlags = ParsedFlags<typeof CALL_FLAGS>;
Expand Down Expand Up @@ -114,14 +115,14 @@ export default defineCommand({
const { serverCode, toolName } = parseTarget(flags.target);
const toolArgs = buildToolArgs(flags);

const url = flags.url || ctx.client.url(bailianMcpPath(serverCode));
const previewUrl = flags.url || ctx.client.url(bailianMcpPath(serverCode));
const format = detectOutputFormat(settings.output);

if (settings.dryRun) {
emitResult(
{
server: serverCode,
url,
url: previewUrl,
tool: toolName,
arguments: toolArgs,
},
Expand All @@ -130,13 +131,14 @@ export default defineCommand({
return;
}

const client = ctx.client.mcp(url);
let client: { close?(): void } | undefined;
try {
await client.initialize();
const result = await client.callTool(toolName, toolArgs);
const connected = await ctx.client.connectBailianMcp(serverCode, flags.url);
client = connected.client;
const result = await connected.client.callTool(toolName, toolArgs);

if (result.isError) {
const errText = result.content.map((c) => c.text || "").join("\n");
const errText = result.content.map((contentItem) => contentItem.text || "").join("\n");
throw new BailianError(`Tool error: ${errText}`);
}

Expand All @@ -146,6 +148,8 @@ export default defineCommand({
rethrowWithMcpActivateHint(error, serverCode);
}
throw error;
} finally {
client?.close?.();
}
},
});
18 changes: 11 additions & 7 deletions packages/commands/src/commands/mcp/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ export default defineCommand({
url: {
type: "string",
valueHint: "<url>",
description: "Override the MCP endpoint URL (for non-Bailian servers)",
description:
"Override the MCP endpoint URL (non-Bailian). Tries Streamable HTTP first, then classic SSE on the same URL.",
},
},
exampleArgs: [
Expand All @@ -28,24 +29,27 @@ export default defineCommand({
const { settings, flags } = ctx;
const code = flags.server;

const url = flags.url || ctx.client.url(bailianMcpPath(code));
const previewUrl = flags.url || ctx.client.url(bailianMcpPath(code));
const format = detectOutputFormat(settings.output);

if (settings.dryRun) {
emitResult({ server: code, url, action: "tools/list" }, format);
emitResult({ server: code, url: previewUrl, action: "tools/list" }, format);
return;
}

const client = ctx.client.mcp(url);
let client: { close?(): void } | undefined;
try {
await client.initialize();
const tools = await client.listTools();
emitResult({ server: code, url, tools }, format);
const connected = await ctx.client.connectBailianMcp(code, flags.url);
client = connected.client;
const tools = await connected.client.listTools();
emitResult({ server: code, url: connected.url, tools }, format);
} catch (error) {
if (!flags.url) {
rethrowWithMcpActivateHint(error, code);
}
throw error;
} finally {
client?.close?.();
}
},
});
36 changes: 36 additions & 0 deletions packages/commands/tests/mcp-activate-hint.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ describe("mcp-activate-hint", () => {
false,
);
expect(isMcpNotActivated(new Error("MCP不存在或未开通"))).toBe(false);
// Nested wrapper phrase must not match (anchored at start).
expect(
isMcpNotActivated(
new BailianError("MCP error (-32000): MCP request failed: 404 Not Found - 未开通"),
),
).toBe(false);
});

test("hint 含对应 server 的 MCP 广场深链", () => {
Expand All @@ -38,6 +44,36 @@ describe("mcp-activate-hint", () => {
expect(mcpActivateHint("WebSearch")).toMatch(/SSE|Streamable HTTP/i);
});

test("WebSearch + 405 streamableHttp 补重开通 hint", () => {
const original = new BailianError(
"MCP request failed: 405 Method Not Allowed - current mcp not support streamableHttp",
ExitCode.GENERAL,
);
try {
rethrowWithMcpActivateHint(original, "WebSearch");
expect.unreachable("should throw");
} catch (error) {
expect(error).toBeInstanceOf(BailianError);
const wrapped = error as BailianError;
expect(wrapped.message).toBe(original.message);
expect(wrapped.hint).toMatch(/SSE|Streamable HTTP|Activate|re-activate/i);
expect(wrapped.hint).toContain(mcpMarketplaceDetailPage("WebSearch"));
}
});

test("非 WebSearch 的 405 streamableHttp 不补 hint(由 fallback 处理)", () => {
const original = new BailianError(
"MCP request failed: 405 Method Not Allowed - current mcp not support streamableHttp",
ExitCode.GENERAL,
);
try {
rethrowWithMcpActivateHint(original, "WebParser");
expect.unreachable("should throw");
} catch (error) {
expect(error).toBe(original);
}
});

test("rethrow 保留原 message,补 hint", () => {
const serverCode = "market-cmapi00073529";
const original = new BailianError(
Expand Down
27 changes: 26 additions & 1 deletion packages/core/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@ import { ExitCode } from "../errors/codes.ts";
import { request, requestJson, type HttpDeps, type RequestOpts } from "./http.ts";
import { buildAcsCanonicalQuery, signAcsRequest, type AcsQueryParams } from "./acs.ts";
import { imageFileToDataUri, isLocalFile, resolveFileUrl } from "../files/upload.ts";
import { McpClient } from "./mcp.ts";
import {
bailianMcpPath,
bailianMcpSsePath,
connectBailianMcpWithFallback,
McpClient,
type McpConnectedClient,
} from "./mcp.ts";
import { callConsoleGateway } from "../console/gateway.ts";
import { refreshAccessToken } from "../auth/refresh-token.ts";
import { maskToken } from "../utils/token.ts";
Expand Down Expand Up @@ -164,6 +170,25 @@ export class Client {
return new McpClient(this.http, url, this.deps.apiCred?.token);
}

/**
* Connect to a Bailian MCP: try Streamable HTTP, then SSE on 405 (except WebSearch).
* `urlOverride` maps to `--url`: Streamable first, then classic SSE on the same URL (405/404).
*/
connectBailianMcp(
serverCode: string,
urlOverride?: string,
): Promise<{ client: McpConnectedClient; url: string }> {
this.requireApi();
return connectBailianMcpWithFallback({
deps: this.http,
authToken: this.deps.apiCred?.token,
httpUrl: this.url(bailianMcpPath(serverCode)),
sseUrl: this.url(bailianMcpSsePath(serverCode)),
serverCode,
urlOverride,
});
}

async console<T>(api: string, data: Record<string, unknown>): Promise<T> {
if (!this.deps.consoleCred) {
throw new BailianError("This command needs a console access token.", ExitCode.AUTH);
Expand Down
16 changes: 14 additions & 2 deletions packages/core/src/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,19 @@ export {
type AcsQueryParams,
type AcsSignConfig,
} from "./acs.ts";
export type { McpTool, McpToolResult } from "./mcp.ts";
export { McpClient, bailianMcpPath } from "./mcp.ts";
export type {
McpTool,
McpToolResult,
McpConnectedClient,
ConnectBailianMcpOptions,
} from "./mcp.ts";
export {
McpClient,
bailianMcpPath,
bailianMcpSsePath,
isStreamableHttpUnsupported,
isUrlOverrideSseFallbackCandidate,
connectBailianMcpWithFallback,
} from "./mcp.ts";
export type { ServerSentEvent } from "./stream.ts";
export { parseSSE } from "./stream.ts";
Loading