Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 能力目录按当前任务引擎读取自定义 MCP 的实际工具 (#5745)

Lizi1093d6b9d927
diff --git a/apps/desktop/src/main/maker-host/__tests__/agentCapabilityCatalog.test.ts b/apps/desktop/src/main/maker-host/__tests__/agentCapabilityCatalog.test.ts
index d827e6e1c8..b7fa3956c6 100644
--- a/apps/desktop/src/main/maker-host/__tests__/agentCapabilityCatalog.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/agentCapabilityCatalog.test.ts
@@ -67,10 +67,71 @@ describe('shared runtime capability discovery', () => {
...context, vendorOptions: { [RUNTIME_MCP_NAMES_KEY]: [] },
}, { server: 'custom' })).toMatchObject({ ok: false, capability: { reason: 'not-mounted-in-current-runtime' } });
expect(await readAgentCapabilityCatalog(providers, context, { server: 'custom' }))
- .toMatchObject({ ok: true, discovery: 'harness-mcp' });
+ .toMatchObject({ ok: false, discovery: 'harness-mcp', errorCode: 'HARNESS_DISCOVERY_UNAVAILABLE' });
expect(factory).not.toHaveBeenCalled();
});
+ describe('servers the engine connects itself', () => {
+ const custom = [{ name: 'custom_omc', toClaudeSdkConfig: vi.fn() }];
+
+ it('lists the tools the caller engine actually holds for the server', async () => {
+ const read = vi.fn(async () => ({ state: 'connected' as const, tools: [
+ { name: 'search', description: 'x'.repeat(400) }, { name: 'open' },
+ ] }));
+ const result = await readAgentCapabilityCatalog(custom, context, { server: 'custom_omc' }, undefined, read);
+ expect(read).toHaveBeenCalledWith('custom_omc');
+ expect(result).toMatchObject({ ok: true, discovery: 'harness-mcp', engineState: 'connected',
+ tools: [{ name: 'search' }, { name: 'open' }] });
+ expect((result as { tools: Array<{ description?: string }> }).tools[0]!.description).toHaveLength(301);
+ expect(custom[0]!.toClaudeSdkConfig).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['not-mounted', '新建任务'],
+ ['no-tools', '连接失败'],
+ ['failed', '连接此服务失败'],
+ ['needs-auth', '授权'],
+ ['pending', '仍在连接'],
+ ['disabled', '已被停用'],
+ ] as const)('names the %s engine state instead of reporting success', async (state, text) => {
+ const result = await readAgentCapabilityCatalog(custom, context, { server: 'custom_omc' }, undefined,
+ async () => ({ state, tools: [] }));
+ expect(result).toMatchObject({ ok: false, errorCode: 'HARNESS_MCP_NOT_READY', engineState: state });
+ expect((result as { message: string }).message).toContain(text);
+ });
+
+ it('distinguishes an engine without a status entry from a failed read and hides failure text', async () => {
+ expect(await readAgentCapabilityCatalog(custom, context, { server: 'custom_omc' }, undefined, async () => null))
+ .toMatchObject({ ok: false, errorCode: 'HARNESS_DISCOVERY_UNAVAILABLE' });
+ const failed = await readAgentCapabilityCatalog(custom, context, { server: 'custom_omc' }, undefined,
+ async () => { throw new Error('HTTP 404 https://omc.example/mcp?token=secret'); });
+ expect(failed).toMatchObject({ ok: false, errorCode: 'HARNESS_DISCOVERY_FAILED' });
+ expect(JSON.stringify(failed)).not.toContain('secret');
+ });
+
+ it('times out a stuck engine read', async () => {
+ vi.useFakeTimers();
+ try {
+ const pending = readAgentCapabilityCatalog(custom, context, { server: 'custom_omc' }, undefined,
+ () => new Promise(() => undefined));
+ await vi.advanceTimersByTimeAsync(8_000);
+ expect(await pending).toMatchObject({ ok: false, errorCode: 'HARNESS_DISCOVERY_FAILED' });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not ask the engine about a server the runtime did not mount', async () => {
+ const read = vi.fn();
+ expect(await readAgentCapabilityCatalog(custom, {
+ ...context, vendorOptions: { [RUNTIME_MCP_NAMES_KEY]: [] },
+ }, { server: 'custom_omc' }, undefined, read)).toMatchObject({
+ ok: false, capability: { reason: 'not-mounted-in-current-runtime' },
+ });
+ expect(read).not.toHaveBeenCalled();
+ });
+ });
+
it('returns an explicit discovery failure without leaking factory errors', async () => {
const result = await readAgentCapabilityCatalog([{ name: 'broken',
capability: { title: 'Broken', description: '', source: 'builtin' },
diff --git a/apps/desktop/src/main/maker-host/agentCapabilityCatalog.ts b/apps/desktop/src/main/maker-host/agentCapabilityCatalog.ts
index 1c9706d213..c89a1b1ca4 100644
--- a/apps/desktop/src/main/maker-host/agentCapabilityCatalog.ts
+++ b/apps/desktop/src/main/maker-host/agentCapabilityCatalog.ts
@@ -1,18 +1,39 @@
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
-import type { McpProvider, McpProviderContext } from '@cindy/maker-core';
+import type {
+ AgentMcpServerToolsReport,
+ AgentMcpServerToolsState,
+ McpProvider,
+ McpProviderContext,
+} from '@cindy/maker-core';
export const RUNTIME_MCP_NAMES_KEY = 'cindyRuntimeMcpServerNames';
export interface AgentCapabilityQuery { server?: string; category?: string; }
+/** The caller session's engine view of one MCP server; null = engine has no such entry. */
+export type HarnessMcpToolsReader = (server: string) => Promise<AgentMcpServerToolsReport | null>;
+
+const HARNESS_READ_TIMEOUT_MS = 8_000;
+const TOOL_DESCRIPTION_MAX_CHARS = 300;
+
+const HARNESS_STATE_MESSAGES: Record<Exclude<AgentMcpServerToolsState, 'connected'>, string> = {
+ 'not-mounted': '当前任务的引擎中没有挂载此服务,通常是任务开始后才添加或修改了它;新建任务后再试。',
+ 'no-tools': '引擎已配置此服务,但在当前任务中没有报告任何工具:可能启动时连接失败(地址错误、服务未运行或鉴权失败)、仍在启动,或服务本身没有工具。请在设置中检查该 MCP 的地址与连接状态,修正后新建任务再试。',
+ failed: '引擎连接此服务失败。请在设置中检查该 MCP 的地址与连接状态,修正后新建任务再试。',
+ 'needs-auth': '此服务需要先完成授权,引擎才能取得它的工具。',
+ pending: '引擎仍在连接此服务,稍后再查询。',
+ disabled: '此服务在当前任务的引擎中已被停用。',
+};
+
/** Read the actual provider registrations. This catalog never grants permissions or starts tools. */
export async function readAgentCapabilityCatalog(
providers: readonly McpProvider[],
context: McpProviderContext,
query: AgentCapabilityQuery,
availability: (provider: McpProvider) => string | null = () => null,
+ readHarnessTools?: HarnessMcpToolsReader,
) {
const declarations = providers.map((provider) => {
let reason: string | null = null;
@@ -42,18 +63,13 @@ export async function readAgentCapabilityCatalog(
const provider = providers.find((item) => item.name === query.server)!;
// External connections are owned by the harness; never start another process,
// inspect its credentials or execute a custom server's business operations.
- if (declaration.source !== 'builtin') return {
- ok: true, capability: declaration, discovery: 'harness-mcp',
- hint: '通过当前引擎已有的 MCP 发现入口查询此连接的工具。',
- };
+ if (declaration.source !== 'builtin') return readHarnessCapability(declaration, readHarnessTools);
let instance: McpServer | undefined;
let client: Client | undefined;
try {
const config = provider.toClaudeSdkConfig?.({ ...context, getSessionContext: () => context });
const candidate = config && typeof config === 'object' && 'instance' in config ? config.instance : undefined;
- if (!(candidate instanceof McpServer)) return {
- ok: true, capability: declaration, discovery: 'harness-mcp',
- };
+ if (!(candidate instanceof McpServer)) return await readHarnessCapability(declaration, readHarnessTools);
instance = candidate;
client = new Client({ name: 'cindy-capability-catalog', version: '1.0.0' });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
@@ -81,3 +97,53 @@ export async function readAgentCapabilityCatalog(
await Promise.allSettled([client?.close(), instance?.close()]);
}
}
+
+/**
+ * Ask the caller session's engine which tools it actually holds for a server it
+ * connects itself. Registration alone is never reported as discovery success,
+ * and engine failure text is not forwarded because it may carry endpoints.
+ */
+async function readHarnessCapability<T extends { server: string }>(
+ declaration: T,
+ readHarnessTools: HarnessMcpToolsReader | undefined,
+) {
+ const base = { capability: declaration, discovery: 'harness-mcp' as const };
+ if (!readHarnessTools) return {
+ ok: false, ...base, errorCode: 'HARNESS_DISCOVERY_UNAVAILABLE',
+ message: '当前引擎没有可供读取的 MCP 工具目录,无法确认此服务在本任务中的工具。',
+ };
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let report: AgentMcpServerToolsReport | null;
+ try {
+ report = await Promise.race([
+ readHarnessTools(declaration.server),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error('timeout')), HARNESS_READ_TIMEOUT_MS);
+ }),
+ ]);
+ } catch {
+ return {
+ ok: false, ...base, errorCode: 'HARNESS_DISCOVERY_FAILED',
+ message: '读取当前引擎的 MCP 工具目录失败,暂时无法确认此服务的工具;稍后重试。',
+ };
+ } finally {
+ clearTimeout(timer);
+ }
+ if (!report) return {
+ ok: false, ...base, errorCode: 'HARNESS_DISCOVERY_UNAVAILABLE',
+ message: '当前引擎没有可供读取的 MCP 工具目录,无法确认此服务在本任务中的工具。',
+ };
+ if (report.state !== 'connected') return {
+ ok: false, ...base, errorCode: 'HARNESS_MCP_NOT_READY', engineState: report.state,
+ message: HARNESS_STATE_MESSAGES[report.state],
+ };
+ return {
+ ok: true, ...base, engineState: report.state,
+ tools: report.tools.map((tool) => tool.description && tool.description.length > TOOL_DESCRIPTION_MAX_CHARS
+ ? { ...tool, description: `${tool.description.slice(0, TOOL_DESCRIPTION_MAX_CHARS)}…` }
+ : tool),
+ hint: report.tools.length > 0
+ ? '以上是当前引擎在本任务中为此服务实际持有的工具(服务端原始名称),引擎会按自身规则命名后提供(通常带服务名前缀)。'
+ : '此服务已连接,但没有提供任何工具。',
+ };
+}
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index c645f9210f..65b6868a63 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -965,7 +965,9 @@ export function getMaker(): Maker {
&& entry?.source === 'builtin' && !REMOTE_ALLOWED_SERVER_NAMES.has(provider.name);
return entry?.available === false || remoteBridgeMissing
? 'transport-unavailable-for-current-runtime' : null;
- });
+ },
+ // The caller's own engine is the only evidence of what this task can call.
+ (server) => session.readMcpServerTools(server));
if (_maker?.getSession(session.id) !== session) return { ok: false, errorCode: 'CALLER_UNAVAILABLE' };
return { ...result, permission: session.stablePermissionModeState,
hostCapabilities: Object.fromEntries(Object.entries(session.capabilities)
diff --git a/docs/dev-rules/agent-capabilities.md b/docs/dev-rules/agent-capabilities.md
index 5a403b8aa6..e37fbf5f1d 100644
--- a/docs/dev-rules/agent-capabilities.md
+++ b/docs/dev-rules/agent-capabilities.md
@@ -6,7 +6,7 @@
- 内置 MCP:在现有 `createLiziMcpProviders` / Desktop provider 注册处声明。`capability` 元数据可提供名称、说明、来源和渐进发现入口;实际工具名称、参数、说明仍从 MCP 注册读取。
- 插件:沿插件自己的 manifest 和 `ghost_list → ghost_info → ghost_call` 发现,不复制为另一套工具。
-- 自定义 MCP:沿现有连接配置及引擎 MCP 发现。目录查询不会另起进程或读出 URL、headers、token。
+- 自定义 MCP:连接由引擎持有。目录查询不会另起进程、调用其工具或读出 URL、headers、token,而是向发起查询的任务所在引擎读取该服务在本任务中实际持有的工具(见下节)。
- 命令行、文件、原生子 Agent:由当前引擎提供。伙伴不再额外禁用;运行时能力摘要和引擎实际提供的工具共同表达可用范围。
- Skill:仍使用既有安装、发现和伙伴自有 Skill 学习体系。工具全部继承不意味着覆盖伙伴人格、共享个人记忆或将全部 Skill 正文塞入上下文。
@@ -24,7 +24,9 @@
{ "scope": "runtime", "server": "cindy_helper", "category": "control" }
```
-读取内置 server 的真实 schema 与渐进目录。没有 `scope` 时保留原产品说明查询行为。宿主交互能力不等于 Agent 已有可调用接口;例如应用安装更新、重启没有正式 Agent 接口,`check_app_update` 只查询当前更新渠道。
+读取内置 server 的真实 schema 与渐进目录。没有 `scope` 时保留原产品说明查询行为。
+
+指定由引擎自己连接的 server(自定义 MCP 等)时,宿主经发起查询的 Session 读取引擎在本任务中的状态:Codex 用带本任务 `threadId` 的 `mcpServerStatus/list`(不拿共享 app-server 的进程级清单代替),Claude Code 用 `mcpServerStatus()`。有工具时返回服务端原始工具名与截短说明;否则返回 `ok: false` 和明确的 `engineState`——`not-mounted`(本任务引擎未挂载,常见于任务开始后才增改)、`no-tools`(已配置但未报告工具,Codex 无法区分启动失败与本无工具)、`failed`、`needs-auth`、`pending`、`disabled`;引擎没有该入口(Pi、SSH 远端 Claude、远程 Agent)报 `HARNESS_DISCOVERY_UNAVAILABLE`,读取失败或超时报 `HARNESS_DISCOVERY_FAILED`。不转发引擎的失败原文,避免带出连接地址。实现见 `apps/desktop/src/main/maker-host/agentCapabilityCatalog.ts` 与 `packages/maker-core/src/agents/{codex,claude-code}/mcp-server-tools.ts`。宿主交互能力不等于 Agent 已有可调用接口;例如应用安装更新、重启没有正式 Agent 接口,`check_app_update` 只查询当前更新渠道。
## 伙伴默认配置
@@ -57,6 +59,7 @@
- `botCanonicalSession.test.ts`:创建、存量配置、同任务刷新、跨引擎/远端可用性和能力修改。
- `botProfileVersioning.test.ts`:旧名单升级、保留权限档、显式选择的幂等保存。
- `botCapabilitySettings.test.tsx`:默认全选及主动取消后的其他能力保留。
-- `agentCapabilityCatalog.test.ts`:真实 SDK schema、渐进目录、未挂载原因和外部连接不被重复启动。
+- `agentCapabilityCatalog.test.ts`:真实 SDK schema、渐进目录、未挂载原因、外部连接不被重复启动,以及引擎实际工具与各类未就绪状态。
+- maker-core `agents/codex/mcp-server-tools.test.ts`、`agents/claude-code/mcp-server-tools.test.ts`:按本任务线程读取、未挂载与无工具的区分。
- `lizi_xdtHelperMcpServer.test.ts`:普通任务/伙伴使用同一个能力查询和通用任务工具。
- 三个引擎各自的伙伴启动回归:没有伙伴专属的原生子 Agent 禁用参数。
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 708760ff06..7c097b7f9c 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -590,8 +590,9 @@ Session 任务遵守同一套机制与呈现契约:
`toolCapabilityVersion: 1` 标记新的声明语义;此后的明确选择(包括空允许名单)照常生效。
- 能力目录来自运行时 provider 注册,不手抄工具数量或另维护底层调用口登记表。
`get_capabilities(scope: runtime)` 返回当前引擎的注册项、启用状态及未挂载原因;指定 `server` 读取
- 真实工具 schema,内置渐进目录可继续按 `category` 展开。插件和外部 MCP 沿原有发现入口展开,
- 不为查目录额外启动外部进程,也不暴露连接凭证。
+ 真实工具 schema,内置渐进目录可继续按 `category` 展开。插件沿原有发现入口展开;外部 MCP 由宿主
+ 向当前任务的引擎读取实际持有的工具,读不到时如实说明未挂载、未报告工具、连接失败、待授权等状态,
+ 不为查目录额外启动外部进程,也不暴露连接凭证(细则见 `docs/dev-rules/agent-capabilities.md`)。
- 本地伙伴的 helper 使用普通任务类目加伙伴类目;远程任务遵循该引擎与传输本来支持的普通能力面。
新工具随注册进入共享目录和默认继承范围,不再要求登记“只有主人那一轮可用”。
- 权限由 Agent 的 ask / auto / bypassPermissions 和现有工具组配置统一处理,包含命令行、文件与 MCP。
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 9fec92ab53..b23946ff47 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -2237,10 +2237,38 @@ export interface PiModelSwitchPreview {
reason?: string;
}
+/**
+ * What the running engine reports for one MCP server in this session.
+ * - `connected`: the engine lists tools for it (possibly none, when it says so).
+ * - `no-tools`: the engine has the server but lists no tools and no state; it
+ * may have failed to start, still be starting, or expose no tools.
+ * - `not-mounted`: the engine has no server by that name in this session.
+ */
+export type AgentMcpServerToolsState =
+ | 'connected'
+ | 'no-tools'
+ | 'not-mounted'
+ | 'failed'
+ | 'needs-auth'
+ | 'pending'
+ | 'disabled';
+
+export interface AgentMcpServerToolsReport {
+ state: AgentMcpServerToolsState;
+ /** Raw MCP tool names as the server declared them, not harness-qualified names. */
+ tools: Array<{ name: string; description?: string }>;
+}
+
export interface AgentSessionHandle {
/** Canonical physical Skill identities frozen at native runtime startup. */
readonly disabledSkillPaths?: readonly string[];
getCodexContextWindowInfo?(): Promise<CodexContextWindowInfo | null>;
+ /**
+ * Read-only: ask the engine which tools it holds for one MCP server in this
+ * session. Never starts a server or calls its tools. Absent, or null, when
+ * the engine has no per-session MCP status entry.
+ */
+ readMcpServerTools?(serverName: string): Promise<AgentMcpServerToolsReport | null>;
/** Native session identity safe for resume; may retain an unaccepted fork's source. */
readonly id: string;
/** Transient native request identity; hosts must not persist it as a resume id. */
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index a794a2bf2e..ae74a737e6 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -45,6 +45,7 @@ import type {
} from '@anthropic-ai/claude-agent-sdk';
import { discoverSubagentDefinitions } from './subagent-definitions.js';
import { spawnObservedClaudeProcess } from './local-process-spawn.js';
+import { claudeMcpServerToolsReport, type ClaudeMcpServerStatusEntry } from './mcp-server-tools.js';
import {
reportSubagentModelDiagnostics,
resolveSubagentModelDefault,
@@ -7256,6 +7257,15 @@ export class ClaudeCodeAgent extends BaseAgent {
return await getContextUsage.call(q) as import('../../types/context-usage.js').ContextUsageData;
},
+ async readMcpServerTools(serverName: string) {
+ // SSH remote queries do not expose MCP status; report no engine entry.
+ const readStatus = (q as {
+ mcpServerStatus?: () => Promise<ClaudeMcpServerStatusEntry[]>;
+ }).mcpServerStatus;
+ if (typeof readStatus !== 'function') return null;
+ return claudeMcpServerToolsReport(await readStatus.call(q), serverName);
+ },
+
setInteractionResolver(resolver: InteractionResolver) {
interactionResolver = resolver;
},
diff --git a/packages/maker-core/src/agents/claude-code/mcp-server-tools.test.ts b/packages/maker-core/src/agents/claude-code/mcp-server-tools.test.ts
new file mode 100644
index 0000000000..16b599c710
--- /dev/null
+++ b/packages/maker-core/src/agents/claude-code/mcp-server-tools.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+import { claudeMcpServerToolsReport } from './mcp-server-tools.js';
+
+describe('Claude MCP server tools report', () => {
+ it('returns the connected server tools as declared', () => {
+ expect(claudeMcpServerToolsReport([
+ { name: 'other', status: 'connected', tools: [{ name: 'x' }] },
+ { name: 'custom_omc', status: 'connected', tools: [{ name: 'search', description: 'Search' }, { name: 'open' }] },
+ ], 'custom_omc')).toEqual({
+ state: 'connected',
+ tools: [{ name: 'search', description: 'Search' }, { name: 'open' }],
+ });
+ });
+
+ it.each(['failed', 'needs-auth', 'pending', 'disabled'] as const)('reports %s without tools', (status) => {
+ expect(claudeMcpServerToolsReport([{ name: 'custom_omc', status, tools: [{ name: 'stale' }] }], 'custom_omc'))
+ .toEqual({ state: status, tools: [] });
+ });
+
+ it('reports an unknown server as not mounted and an unknown state by its tools', () => {
+ expect(claudeMcpServerToolsReport([], 'custom_omc')).toEqual({ state: 'not-mounted', tools: [] });
+ expect(claudeMcpServerToolsReport([{ name: 'custom_omc', status: 'reconnecting' }], 'custom_omc'))
+ .toEqual({ state: 'no-tools', tools: [] });
+ });
+});
diff --git a/packages/maker-core/src/agents/claude-code/mcp-server-tools.ts b/packages/maker-core/src/agents/claude-code/mcp-server-tools.ts
new file mode 100644
index 0000000000..f6bb066326
--- /dev/null
+++ b/packages/maker-core/src/agents/claude-code/mcp-server-tools.ts
@@ -0,0 +1,28 @@
+import type { AgentMcpServerToolsReport, AgentMcpServerToolsState } from '../base-agent.js';
+
+/** Subset of the SDK's `McpServerStatus` this report reads. */
+export interface ClaudeMcpServerStatusEntry {
+ name: string;
+ status: string;
+ tools?: Array<{ name: string; description?: string }>;
+}
+
+const ENGINE_STATES = new Set<string>(['connected', 'failed', 'needs-auth', 'pending', 'disabled']);
+
+/** Map `query.mcpServerStatus()` to one server's report; failure text is not forwarded. */
+export function claudeMcpServerToolsReport(
+ statuses: readonly ClaudeMcpServerStatusEntry[],
+ serverName: string,
+): AgentMcpServerToolsReport {
+ const server = statuses.find((entry) => entry.name === serverName);
+ if (!server) return { state: 'not-mounted', tools: [] };
+ const tools = (server.tools ?? [])
+ .filter((tool) => typeof tool?.name === 'string' && tool.name)
+ .map((tool) => typeof tool.description === 'string' && tool.description
+ ? { name: tool.name, description: tool.description }
+ : { name: tool.name });
+ const state: AgentMcpServerToolsState = ENGINE_STATES.has(server.status)
+ ? server.status as AgentMcpServerToolsState
+ : tools.length > 0 ? 'connected' : 'no-tools';
+ return { state, tools: state === 'connected' ? tools : [] };
+}
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index c62872bb52..5c2e2cc570 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -40,6 +40,7 @@ import { randomUUID } from 'node:crypto';
import { promises as fs } from 'node:fs';
import { structuredPatch } from 'diff';
import { syncCodexArchiveState } from './archive-state.js';
+import { readCodexThreadMcpServerTools } from './mcp-server-tools.js';
import {
BaseAgent,
@@ -14120,6 +14121,12 @@ assertRouteCurrent();
} catch { return null; }
},
+ readMcpServerTools: (serverName: string) => readCodexThreadMcpServerTools(
+ (method, params, requestOpts) => host.request(method, params, requestOpts),
+ threadId,
+ serverName,
+ ),
+
getUsageSnapshot(): UsageSnapshot {
return liveUsageSnapshot();
},
diff --git a/packages/maker-core/src/agents/codex/mcp-server-tools.test.ts b/packages/maker-core/src/agents/codex/mcp-server-tools.test.ts
new file mode 100644
index 0000000000..637c11be17
--- /dev/null
+++ b/packages/maker-core/src/agents/codex/mcp-server-tools.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it, vi } from 'vitest';
+import { readCodexThreadMcpServerTools } from './mcp-server-tools.js';
+
+type Page = { data: Array<Record<string, unknown>>; nextCursor: string | null };
+
+function requestFor(pages: Record<string, Page>) {
+ const request = vi.fn(async (_method: string, params: Record<string, unknown>) =>
+ pages[String(params.cursor ?? 'first')]!);
+ return { request, invoke: request as Parameters<typeof readCodexThreadMcpServerTools>[0] };
+}
+
+describe('Codex thread MCP server tools', () => {
+ it('reads the caller thread status, not the shared host list', async () => {
+ const { request, invoke } = requestFor({ first: { nextCursor: null, data: [
+ { name: 'custom_omc', authStatus: 'bearerToken', tools: {
+ search: { name: 'search', description: 'Search OMC', inputSchema: {} },
+ open: { name: 'open', inputSchema: {} },
+ } },
+ ] } });
+ expect(await readCodexThreadMcpServerTools(invoke, 'thread-1', 'custom_omc')).toEqual({
+ state: 'connected',
+ tools: [{ name: 'search', description: 'Search OMC' }, { name: 'open' }],
+ });
+ expect(request).toHaveBeenCalledWith('mcpServerStatus/list',
+ { cursor: null, limit: 100, detail: 'toolsAndAuthOnly', threadId: 'thread-1' },
+ expect.objectContaining({ timeoutMs: expect.any(Number) }));
+ });
+
+ it('keeps a configured server without tools distinct from one the thread never mounted', async () => {
+ const { invoke } = requestFor({ first: { nextCursor: 'next', data: [
+ { name: 'custom_omc', authStatus: 'unsupported', tools: {} },
+ { name: 'oauth_server', authStatus: 'notLoggedIn', tools: {} },
+ ] }, next: { nextCursor: null, data: [{ name: 'other', tools: { a: {} } }] } });
+ expect(await readCodexThreadMcpServerTools(invoke, 't', 'custom_omc'))
+ .toEqual({ state: 'no-tools', tools: [] });
+ expect(await readCodexThreadMcpServerTools(invoke, 't', 'oauth_server'))
+ .toEqual({ state: 'needs-auth', tools: [] });
+ expect(await readCodexThreadMcpServerTools(invoke, 't', 'missing'))
+ .toEqual({ state: 'not-mounted', tools: [] });
+ });
+
+ it('rejects a repeating cursor instead of looping', async () => {
+ const { invoke } = requestFor({
+ first: { nextCursor: 'a', data: [] },
+ a: { nextCursor: 'a', data: [] },
+ });
+ await expect(readCodexThreadMcpServerTools(invoke, 't', 'custom_omc')).rejects.toThrow(/repeated a cursor/);
+ });
+});
diff --git a/packages/maker-core/src/agents/codex/mcp-server-tools.ts b/packages/maker-core/src/agents/codex/mcp-server-tools.ts
new file mode 100644
index 0000000000..bad10854a8
--- /dev/null
+++ b/packages/maker-core/src/agents/codex/mcp-server-tools.ts
@@ -0,0 +1,59 @@
+import type { AgentMcpServerToolsReport } from '../base-agent.js';
+import {
+ Method,
+ type CodexMcpServerStatus,
+ type CodexMcpServerStatusListResponse,
+} from './app-server/protocol.js';
+
+const MAX_STATUS_PAGES = 5;
+
+type StatusRequest = <T>(
+ method: string,
+ params: Record<string, unknown>,
+ opts: { timeoutMs: number },
+) => Promise<T>;
+
+/**
+ * Read one MCP server's tools from this thread's own MCP status. The shared
+ * app-server's process-level list is not evidence for a thread, so `threadId`
+ * is always sent. Read-only: never starts a server or calls its tools.
+ */
+export async function readCodexThreadMcpServerTools(
+ request: StatusRequest,
+ threadId: string,
+ serverName: string,
+ timeoutMs = 5_000,
+): Promise<AgentMcpServerToolsReport> {
+ const deadline = Date.now() + timeoutMs;
+ const seenCursors = new Set<string>();
+ let cursor: string | null = null;
+ for (let page = 0; page < MAX_STATUS_PAGES; page++) {
+ const remainingMs = deadline - Date.now();
+ if (remainingMs <= 0) throw new Error('Codex MCP status timed out');
+ const status: CodexMcpServerStatusListResponse = await request<CodexMcpServerStatusListResponse>(
+ Method.McpServerStatusList,
+ { cursor, limit: 100, detail: 'toolsAndAuthOnly', threadId },
+ { timeoutMs: remainingMs },
+ );
+ const server = status.data.find((entry) => entry.name === serverName);
+ if (server) return reportFromCodexStatus(server);
+ cursor = status.nextCursor;
+ if (cursor === null) return { state: 'not-mounted', tools: [] };
+ if (seenCursors.has(cursor)) throw new Error('Codex MCP status pagination repeated a cursor');
+ seenCursors.add(cursor);
+ }
+ throw new Error(`Codex MCP status pagination exceeded ${MAX_STATUS_PAGES} pages`);
+}
+
+function reportFromCodexStatus(server: CodexMcpServerStatus): AgentMcpServerToolsReport {
+ const tools = Object.entries(server.tools ?? {}).map(([name, tool]) => {
+ const description = tool && typeof tool === 'object'
+ ? (tool as { description?: unknown }).description
+ : undefined;
+ return typeof description === 'string' && description ? { name, description } : { name };
+ });
+ if (tools.length > 0) return { state: 'connected', tools };
+ // Codex lists configured servers even when their startup failed and reports
+ // no per-server startup state, so an empty tool map stays ambiguous.
+ return { state: server.authStatus === 'notLoggedIn' ? 'needs-auth' : 'no-tools', tools: [] };
+}
diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.ts
index a6c929af98..fce31a195f 100644
--- a/packages/maker-core/src/maker.test.ts
+++ b/packages/maker-core/src/maker.test.ts
@@ -2166,6 +2166,24 @@ describe('Maker session capabilities', () => {
});
});
+describe('Session engine MCP tool status', () => {
+ it('reads the live engine and reports an engine without a status entry as null', async () => {
+ const read = vi.fn(async () => ({ state: 'connected' as const, tools: [{ name: 'search' }] }));
+ const codex = createAgent(async (opts) => ({
+ ...createHandle({ id: opts.sessionId ?? 'with-status' }), readMcpServerTools: read,
+ }));
+ const pi = createAgent(async (opts) => createHandle({ id: opts.sessionId ?? 'plain', agentKind: 'pi' }), 'pi');
+ const maker = new Maker({ agents: { codex, pi }, storage: createStorage(), logger: createLogger() });
+ try {
+ const withStatus = await maker.createSession({ id: 'with-status', agentKind: 'codex', workingDir: '/repo', model: 'm' });
+ const plain = await maker.createSession({ id: 'plain', agentKind: 'pi', workingDir: '/repo', model: 'm' });
+ expect(await withStatus.readMcpServerTools('custom_omc')).toEqual({ state: 'connected', tools: [{ name: 'search' }] });
+ expect(read).toHaveBeenCalledWith('custom_omc');
+ expect(await plain.readMcpServerTools('custom_omc')).toBeNull();
+ } finally { await maker.shutdown(); }
+ });
+});
+
describe('Maker Pi runtime skill status', () => {
it('keeps managed skills pinned to the active session launch snapshot', async () => {
const managedPath = '/managed/context-mode/SKILL.md';
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 08ca6685cd..751fc848d7 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -58,6 +58,7 @@ import { isTerminalAgentErrorEvent, parseToolLoopErrorDetails, isTurnWatchdogLiv
import type { ContextUsageData } from './types/context-usage.js';
import type { PiRuntimeCapabilityManifest } from './types/pi-runtime-capabilities.js';
import type {
+ AgentMcpServerToolsReport,
AgentSessionHandle,
PiModelSwitchPreview,
AgentSessionTeardownOptions,
@@ -1619,6 +1620,15 @@ export class Session {
return this.handle.getContextUsage();
}
+ /**
+ * The engine's own view of one MCP server in this session. Null when the
+ * engine has no per-session MCP status entry; never starts or calls a server.
+ */
+ async readMcpServerTools(serverName: string): Promise<AgentMcpServerToolsReport | null> {
+ this.ensureActive();
+ return await this.handle.readMcpServerTools?.(serverName) ?? null;
+ }
+
/**
* 当前 session 生命周期状态 ('active' / 'aborting' / 'closed' / 'error')。
* 这是内存里的 SDK 子进程视角, 不持久化。区分: