Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions packages/cli/src/acp-integration/session/Session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7399,6 +7399,32 @@ describe('Session', () => {
}
});

it('injects MCP server context for @mcp mentions', async () => {
mockConfig.getMcpServers = vi.fn().mockReturnValue({ demo: {} });
mockConfig.getPromptRegistry = vi.fn().mockReturnValue({
getPromptsByServer: (name: string) => (name === 'demo' ? ['p'] : []),
});
mockConfig.getResourceRegistry = vi.fn().mockReturnValue({
getResourcesByServer: (name: string) =>
name === 'demo' ? [{ uri: 'res://1' }] : [],
});
mockChat.sendMessageStream = vi
.fn()
.mockResolvedValue(createEmptyStream());

await session.prompt({
sessionId: 'test-session-id',
prompt: [{ type: 'text', text: 'Use @mcp:demo now' }],
});

const message = firstSentMessage();
expect(message[0]).toEqual({ text: 'Use @mcp:demo now' });
const sentText = textParts(message).join('\n');
expect(sentText).toContain('--- MCP Server: demo ---');
expect(sentText).toContain('- Resources: 1');
expect(sentText).toContain('- Prompts: 1');
});

it('dedupes repeated extension mentions and skips unknown mentions', async () => {
const extension = makeExtension();
mockConfig.getActiveExtensions = vi.fn().mockReturnValue([extension]);
Expand Down
54 changes: 52 additions & 2 deletions packages/cli/src/acp-integration/session/Session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,11 @@ import {
matchExtensionByRef,
parseExtensionRef,
} from '../../utils/extension-mention.js';
import {
buildMcpServerContextText,
matchMcpServerByRef,
parseMcpServerRef,
} from '../../utils/mcp-server-mention.js';

// Import modular session components
import type {
Expand Down Expand Up @@ -686,6 +691,20 @@ function collectExtensionMentionRefs(
}
}

function collectMcpServerMentionRefs(
text: string,
mentions: Map<string, string>,
): void {
for (const match of text.matchAll(AT_TOKEN_RE)) {
const pathName = match[1];
if (!pathName) continue;
const ref = parseMcpServerRef(pathName);
if (ref) {
mentions.set(ref.name.toLowerCase(), ref.name);
}
}
}

export interface AvailableCommandsSnapshot {
availableCommands: AvailableCommand[];
availableSkills?: string[];
Expand Down Expand Up @@ -5373,6 +5392,7 @@ export class Session implements SessionContext {

const embeddedContext: EmbeddedResourceResource[] = [];
const extensionMentions = new Map<string, string>();
const mcpServerMentions = new Map<string, string>();
const preserveUnsupportedImageForBridge = shouldRunVisionBridge(
this.config,
);
Expand All @@ -5381,6 +5401,7 @@ export class Session implements SessionContext {
switch (part.type) {
case 'text':
collectExtensionMentionRefs(part.text, extensionMentions);
collectMcpServerMentionRefs(part.text, mcpServerMentions);
return { text: part.text };
case 'image':
if (preserveUnsupportedImageForBridge) {
Expand Down Expand Up @@ -5433,18 +5454,21 @@ export class Session implements SessionContext {
extensionMentions,
abortSignal,
);
const mcpServerParts =
this.#resolveMcpServerMentionParts(mcpServerMentions);

if (
atPathCommandParts.length === 0 &&
embeddedContext.length === 0 &&
extensionParts.length === 0
extensionParts.length === 0 &&
mcpServerParts.length === 0
) {
return this.#applyVisionBridgeIfNeeded(parts, abortSignal);
}

if (atPathCommandParts.length === 0 && embeddedContext.length === 0) {
return this.#applyVisionBridgeIfNeeded(
[...parts, ...extensionParts],
[...parts, ...extensionParts, ...mcpServerParts],
abortSignal,
);
}
Expand Down Expand Up @@ -5493,6 +5517,7 @@ export class Session implements SessionContext {
// Add initial query text first
processedQueryParts.push({ text: initialQueryText });
processedQueryParts.push(...extensionParts);
processedQueryParts.push(...mcpServerParts);

// Then add content parts (preserving binary files as inlineData)
for (const part of contentParts) {
Expand All @@ -5507,6 +5532,7 @@ export class Session implements SessionContext {
} else {
processedQueryParts.push({ text: initialQueryText.trim() });
processedQueryParts.push(...extensionParts);
processedQueryParts.push(...mcpServerParts);
}

// Process embedded context from resource blocks
Expand Down Expand Up @@ -5650,6 +5676,30 @@ export class Session implements SessionContext {
return extensionParts;
}

#resolveMcpServerMentionParts(
mcpServerMentions: Map<string, string>,
): Part[] {
if (mcpServerMentions.size === 0) return [];
const servers = this.config.getMcpServers?.() ?? {};
if (Object.keys(servers).length === 0) return [];

const parts: Part[] = [];
for (const name of mcpServerMentions.values()) {
const matched = matchMcpServerByRef(name, servers);
if (!matched) {
this.debug(
`MCP server "${name}" not found among configured MCP servers. ` +
`Available: ${Object.keys(servers).join(', ') || '(none)'}`,
);
continue;
}
parts.push({
text: buildMcpServerContextText(this.config, matched.serverName),
});
}
return parts;
}

debug(msg: string): void {
if (this.config.getDebugMode()) {
debugLogger.warn(msg);
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/i18n/locales/en.js
Original file line number Diff line number Diff line change
Expand Up @@ -1390,6 +1390,7 @@ export default {
'Size:': 'Size:',
'{{count}} bytes': '{{count}} bytes',
'Reference in chat': 'Reference in chat',
'MCP server': 'MCP server',
'MCP resource server': 'MCP resource server',

// Invalid tool related translations
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/i18n/locales/zh-TW.js
Original file line number Diff line number Diff line change
Expand Up @@ -1225,6 +1225,7 @@ export default {
'Size:': '大小:',
'{{count}} bytes': '{{count}} 位元組',
'Reference in chat': '在對話中引用',
'MCP server': 'MCP 伺服器',
'MCP resource server': 'MCP 資源伺服器',
'{{count}} invalid tools': '{{count}} 個無效工具',
invalid: '無效',
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/i18n/locales/zh.js
Original file line number Diff line number Diff line change
Expand Up @@ -1330,6 +1330,7 @@ export default {
'Size:': '大小:',
'{{count}} bytes': '{{count}} 字节',
'Reference in chat': '在对话中引用',
'MCP server': 'MCP 服务器',
'MCP resource server': 'MCP 资源服务器',

// Invalid tool related translations
Expand Down
61 changes: 61 additions & 0 deletions packages/cli/src/ui/hooks/atCommandProcessor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ describe('handleAtCommand', () => {
getPromptRegistry: () => ({
getPromptsByServer: () => [],
}),
getResourceRegistry: () => ({
getResourcesByServer: () => [],
}),
getDebugMode: () => false,
getFileExclusions: () => ({
getCoreIgnorePatterns: () => COMMON_IGNORE_PATTERNS,
Expand Down Expand Up @@ -264,6 +267,36 @@ describe('handleAtCommand', () => {
);
});

it('should inject MCP server context for @mcp mentions', async () => {
mockConfig = {
...mockConfig,
getMcpServers: () => ({ demo: {} }),
getPromptRegistry: () => ({
getPromptsByServer: (name: string) => (name === 'demo' ? ['p'] : []),
}),
getResourceRegistry: () => ({
getResourcesByServer: (name: string) =>
name === 'demo' ? [{ uri: 'res://1' }] : [],
}),
} as unknown as Config;

const result = await handleAtCommand({
query: 'Use @mcp:demo now',
config: mockConfig,
onDebugMessage: mockOnDebugMessage,
messageId: 128,
signal: abortController.signal,
});

expect(result.shouldProceed).toBe(true);
expect(result.processedQuery).toEqual([
{ text: 'Use @mcp:demo now' },
{
text: expect.stringContaining('--- MCP Server: demo ---'),
},
]);
});

it('should handle query with text before and after @command', async () => {
const fileContent = 'Markdown content.';
const filePath = await createTestFile(
Expand Down Expand Up @@ -1315,6 +1348,34 @@ describe('handleAtCommand', () => {
expect(result.filesRead).toContain('myserver:res://doc');
});

it('preserves @mcp:<uri> as a resource ref when a server is named mcp', async () => {
const readMcpResource = vi.fn().mockResolvedValue({
contents: [{ uri: 'res://doc', text: 'RESOURCE BODY' }],
});
const config = {
...mockConfig,
getMcpServers: () => ({ mcp: {}, demo: {} }),
getToolRegistry: () => ({ readMcpResource }),
} as unknown as Config;

const result = await handleAtCommand({
query: 'Use @mcp:res://doc now',
config,
onDebugMessage: mockOnDebugMessage,
messageId: 606,
signal: abortController.signal,
});

expect(readMcpResource).toHaveBeenCalledWith('mcp', 'res://doc', {
signal: abortController.signal,
});
const parts = result.processedQuery as Array<{ text?: string }>;
const text = parts.map((part) => part.text ?? '').join('\n');
expect(text).toContain('Use @mcp:res://doc now');
expect(text).toContain('RESOURCE BODY');
expect(text).not.toContain('--- MCP Server: demo ---');
});

it('injects both a @file and a @server:uri resource, surfacing both tool cards', async () => {
const fileContent = 'FILE BODY';
const filePath = await createTestFile(
Expand Down
Loading
Loading