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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,6 +39,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Upgraded `@opentelemetry/core` to `^2.8.0`. [#1413](https://github.com/sourcebot-dev/sourcebot/pull/1413)
- [EE] Fixed connector setup dialogs to add scrolling when connector setup content goes out of view.
- Fixed Gitea sync failing with `ERR_STREAM_PREMATURE_CLOSE` by forcing identity encoding on the Gitea API fetch and guarding against null repository responses. [#1405](https://github.com/sourcebot-dev/sourcebot/pull/1405)
- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Missing PR link in CHANGELOG entry.

Unlike the surrounding entries, this new line has no trailing [#<id>](url) link. As per coding guidelines, "Update CHANGELOG.md with an entry under [Unreleased] linking to the new PR" and "CHANGELOG.md entries must follow the format: single sentence description followed by a link in the format [#<id>](https://github.com/sourcebot-dev/sourcebot/pull/<id>)."

📝 Proposed fix
-- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.+- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI. [`#1423`](https://github.com/sourcebot-dev/sourcebot/pull/1423)
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
-[EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.
-[EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.[`#1423`](https://github.com/sourcebot-dev/sourcebot/pull/1423)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@CHANGELOG.md` at line 35, The new CHANGELOG.md entry under [Unreleased] is
missing the required pull request link. Update the entry so the single-sentence
description is followed by the matching
[#<id>](https://github.com/sourcebot-dev/sourcebot/pull/<id>) link, consistent
with the surrounding CHANGELOG entries and the project’s CHANGELOG formatting
rules.

Source: Coding guidelines


## [5.0.4] - 2026-06-18

Expand Down
56 changes: 56 additions & 0 deletions packages/web/src/ee/features/chat/agent.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -265,6 +265,62 @@ beforeEach(() => {
});

describe('createMessageStream approval continuation', () => {
test('streams raw MCP tool names for client display', async () => {
const { getConnectedMcpClients } = await import('@/ee/features/chat/mcp/mcpClientFactory');
const { getMcpTools } = await import('@/ee/features/chat/mcp/mcpToolSets');
vi.mocked(getConnectedMcpClients).mockResolvedValueOnce([
{ serverId: 'server-backstage', serverName: 'Backstage' },
] as never);
vi.mocked(getMcpTools).mockResolvedValueOnce({
tools: {},
failedServers: [],
serverFaviconUrls: {
backstage: 'https://backstage.example.com/favicon.ico',
},
toolDisplayNames: {
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
},
cleanup: vi.fn(),
});
mockAi.streamText.mockReturnValue(createFakeStreamResult());

await createMessageStream({
chatId: 'chat-id',
messages: [createUserMessage()],
selectedRepos: [],
disabledMcpServerIds: [],
prisma: {},
model: {},
modelName: 'test-model',
promptCacheStrategy: noopStrategy,
onFinish: vi.fn(),
onError: () => 'error',
userId: 'user-id',
orgId: 1,
} as unknown as Parameters<typeof createMessageStream>[0]);

const execute = mockAi.latestCreateUIMessageStreamOptions?.execute;
if (!execute) {
throw new Error('Expected createUIMessageStream to capture execute callback.');
}

const write = vi.fn();
await execute({
writer: {
merge: vi.fn(),
write,
},
});

expect(write).toHaveBeenCalledWith({
type: 'data-mcp-tool',
data: {
modelToolName: 'mcp_backstage__catalog_query-catalog-entities',
rawToolName: 'catalog.query-catalog-entities',
},
});
});

test.each([
['dynamic', dynamicApprovalRespondedPart],
['static', staticApprovalRespondedPart],
Expand Down
13 changes: 12 additions & 1 deletion packages/web/src/ee/features/chat/agent.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -369,6 +369,12 @@ export const createMessageStream = async ({
data: { sanitizedName, faviconUrl },
});
},
onMcpToolDiscovered: (modelToolName, rawToolName) => {
writer.write({
type: 'data-mcp-tool',
data: { modelToolName, rawToolName },
});
},
onMcpServerFailed: (serverName) => {
writer.write({
type: 'data-mcp-failed-server',
Expand DownExpand Up@@ -501,6 +507,7 @@ interface AgentOptions {
inputSources: Source[];
onWriteSource: (source: Source) => void;
onMcpServerDiscovered: (sanitizedName: string, faviconUrl: string) => void;
onMcpToolDiscovered: (modelToolName: string, rawToolName: string) => void;
onMcpServerFailed: (serverName: string) => void;
traceId: string;
chatId: string;
Expand All@@ -520,6 +527,7 @@ const createAgentStream = async ({
disabledMcpServerIds,
onWriteSource,
onMcpServerDiscovered,
onMcpToolDiscovered,
onMcpServerFailed,
traceId,
chatId,
Expand DownExpand Up@@ -556,7 +564,7 @@ const createAgentStream = async ({
}))
).filter((source) => source !== undefined);

let mcpToolSetsObj: McpToolsResult = { tools: {}, failedServers: [], serverFaviconUrls: {}, cleanup: async () => {} };
let mcpToolSetsObj: McpToolsResult = { tools: {}, failedServers: [], serverFaviconUrls: {}, toolDisplayNames: {}, cleanup: async () => {} };
if (userId && orgId && await hasEntitlement('ask') && disabledMcpServerIds !== undefined) {
try {
const allMcpClients = await getConnectedMcpClients(prisma, userId, orgId);
Expand All@@ -570,6 +578,9 @@ const createAgentStream = async ({
for (const [sanitizedName, faviconUrl] of Object.entries(mcpToolSetsObj.serverFaviconUrls)) {
onMcpServerDiscovered(sanitizedName, faviconUrl);
}
for (const [modelToolName, rawToolName] of Object.entries(mcpToolSetsObj.toolDisplayNames)) {
onMcpToolDiscovered(modelToolName, rawToolName);
}

if (mcpClients.length > 0) {
logger.info(`Connected to ${mcpClients.length} external MCP server(s): ${mcpClients.map(c => c.serverName).join(', ')}`);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ import { duplicateChat } from '@/features/chat/actions';
import { generateAndUpdateChatNameFromMessage } from '@/ee/features/chat/actions';
import { isServiceError } from '@/lib/utils';
import { NotConfiguredErrorBanner } from '@/features/chat/components/notConfiguredErrorBanner';
import { McpServerIconContext, McpServerIconMap} from '../../mcpServerIconContext';
import { McpServerIconContext, McpServerIconMap, McpToolNameContext, McpToolNameMap } from '../../mcpDisplayMetadataContext';
import { ToolApprovalProvider } from '../../toolApprovalContext';
import useCaptureEvent from '@/hooks/useCaptureEvent';
import { SignInPromptBanner } from './signInPromptBanner';
Expand DownExpand Up@@ -107,6 +107,18 @@ export const ChatThread = ({
return map;
});

const [mcpToolNameMap, setMcpToolNameMap] = useState<McpToolNameMap>(() => {
const map: McpToolNameMap = {};
initialMessages?.forEach((message) => {
message.parts
.filter((part) => part.type === 'data-mcp-tool')
.forEach((part) => {
map[part.data.modelToolName] = part.data.rawToolName;
});
});
return map;
});

const [failedMcpServers, setFailedMcpServers] = useState<string[]>(() => {
const names: string[] = [];
initialMessages?.forEach((message) => {
Expand DownExpand Up@@ -176,6 +188,12 @@ export const ChatThread = ({
[dataPart.data.sanitizedName]: dataPart.data.faviconUrl,
}));
}
if (dataPart.type === 'data-mcp-tool') {
setMcpToolNameMap((prev) => ({
...prev,
[dataPart.data.modelToolName]: dataPart.data.rawToolName,
}));
}
if (dataPart.type === 'data-mcp-failed-server') {
setFailedMcpServers((prev) => {
if (prev.includes(dataPart.data.serverName)) {
Expand DownExpand Up@@ -378,6 +396,7 @@ export const ChatThread = ({
return (
<ToolApprovalProvider value={addToolApprovalResponse}>
<McpServerIconContext.Provider value={mcpServerIconMap}>
<McpToolNameContext.Provider value={mcpToolNameMap}>
<ChatPaneDropzone
className="flex flex-col flex-1 min-h-0 w-full"
onFilesDropped={(files) => chatBoxRef.current?.addFiles(files)}
Expand DownExpand Up@@ -526,6 +545,7 @@ export const ChatThread = ({
)}
</div>
</ChatPaneDropzone>
</McpToolNameContext.Provider>
</McpServerIconContext.Provider>
</ToolApprovalProvider>
);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -546,6 +546,7 @@ export const StepPartRenderer = ({ part, toolTokenUsageMap }: { part: SBChatMess
case 'data-source':
case 'data-command':
case 'data-mcp-server':
case 'data-mcp-tool':
case 'data-mcp-failed-server':
case 'data-attachment':
case 'file':
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,14 @@

import { Button } from "@/components/ui/button";
import { McpFavicon } from "@/ee/features/chat/mcp/components/mcpFavicon";
import { useMcpServerIconMap} from "@/ee/features/chat/mcpServerIconContext";
import { McpToolNameMap, useMcpServerIconMap, useMcpToolNameMap } from "@/ee/features/chat/mcpDisplayMetadataContext";
import { useToolApproval } from "@/ee/features/chat/toolApprovalContext";
import { SBChatToolPart } from "@/features/chat/utils";
import { cn } from "@/lib/utils";
import { getToolName } from "ai";
import { ChevronRight } from "lucide-react";
import { useCallback, useState } from "react";
import { parseMcpToolName } from "./tools/mcpToolComponent";
import { getMcpToolDisplayParts } from "./tools/mcpToolComponent";
import { JsonHighlighter } from "./tools/jsonHighlighter";

export type ApprovalRequestedToolPart = SBChatToolPart & {
Expand All@@ -23,6 +23,7 @@ interface ToolApprovalBannerProps {
export const ToolApprovalBanner = ({ parts }: ToolApprovalBannerProps) => {
const addToolApprovalResponse = useToolApproval();
const iconMap = useMcpServerIconMap();
const rawToolNames = useMcpToolNameMap();

if (parts.length === 0) {
return null;
Expand All@@ -36,6 +37,7 @@ export const ToolApprovalBanner = ({ parts }: ToolApprovalBannerProps) => {
part={part}
addToolApprovalResponse={addToolApprovalResponse}
iconMap={iconMap}
rawToolNames={rawToolNames}
/>
))}
</div>
Expand All@@ -46,17 +48,17 @@ const ToolApprovalItem = ({
part,
addToolApprovalResponse,
iconMap,
rawToolNames,
}: {
part: ApprovalRequestedToolPart;
addToolApprovalResponse: ReturnType<typeof useToolApproval>;
iconMap: Record<string, string | undefined>;
rawToolNames: McpToolNameMap;
}) => {
const [isExpanded, setIsExpanded] = useState(false);
const partToolName = getToolName(part);
const parsed = parseMcpToolName(partToolName);
const serverName = parsed?.serverName ?? partToolName;
const toolName = parsed?.toolName ?? partToolName;
const faviconUrl = parsed ? iconMap[parsed.serverName] : undefined;
const display = getMcpToolDisplayParts(partToolName, rawToolNames);
const faviconUrl = display.serverName ? iconMap[display.serverName] : undefined;

const requestText = JSON.stringify(part.input, null, 2);

Expand All@@ -83,13 +85,13 @@ const ToolApprovalItem = ({
>
<McpFavicon faviconUrl={faviconUrl} className="w-4 h-4" />
<span className="text-sm text-foreground truncate">
{parsed ? (
{display.serverName ? (
<>
Agent wants to use <span className="font-medium">{toolName}</span> from <span className="font-medium">{serverName}</span>
Agent wants to use <span className="font-medium">{display.toolName}</span> from <span className="font-medium">{display.serverName}</span>
</>
) : (
<>
Agent wants to use <span className="font-medium">{toolName}</span>
Agent wants to use <span className="font-medium">{display.toolName}</span>
</>
)}
</span>
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
import { render, screen } from '@testing-library/react';
import type { DynamicToolUIPart } from 'ai';
import { describe, expect, test } from 'vitest';
import { McpToolNameContext } from '@/ee/features/chat/mcpDisplayMetadataContext';
import { getMcpToolDisplayParts, McpToolComponent } from './mcpToolComponent';

describe('getMcpToolDisplayParts', () => {
test('maps provider-safe MCP tool names back to raw tool names for display', () => {
expect(getMcpToolDisplayParts(
'mcp_backstage__catalog_query-catalog-entities',
{
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
},
)).toEqual({
serverName: 'backstage',
toolName: 'catalog.query-catalog-entities',
displayName: 'backstage: catalog.query-catalog-entities',
});
});

test('falls back to the provider-safe name for older messages without metadata', () => {
expect(getMcpToolDisplayParts('mcp_backstage__catalog_query-catalog-entities')).toEqual({
serverName: 'backstage',
toolName: 'catalog_query-catalog-entities',
displayName: 'backstage: catalog_query-catalog-entities',
});
});
});

describe('McpToolComponent', () => {
test('renders the raw MCP tool name when display metadata is available', () => {
const part = {
type: 'dynamic-tool',
toolName: 'mcp_backstage__catalog_query-catalog-entities',
toolCallId: 'tool-call-1',
state: 'approval-requested',
input: { filter: 'kind=component' },
} as DynamicToolUIPart;

render(
<McpToolNameContext.Provider value={{
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
}}>
<McpToolComponent part={part} />
</McpToolNameContext.Provider>
);

expect(screen.getByText('backstage: catalog.query-catalog-entities')).toBeTruthy();
expect(screen.getByText('Request (backstage: catalog.query-catalog-entities)')).toBeTruthy();
expect(screen.queryByText('backstage: catalog_query-catalog-entities')).toBeNull();
});
});
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all \u003cpre\u003e\u003ccode\u003e blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks"); } } catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); } })(); (function(){ try { var __m = "github.com"; var __re = new RegExp('^' + "github\\.com" + '
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,6 +39,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Upgraded `@opentelemetry/core` to `^2.8.0`. [#1413](https://github.com/sourcebot-dev/sourcebot/pull/1413)
- [EE] Fixed connector setup dialogs to add scrolling when connector setup content goes out of view.
- Fixed Gitea sync failing with `ERR_STREAM_PREMATURE_CLOSE` by forcing identity encoding on the Gitea API fetch and guarding against null repository responses. [#1405](https://github.com/sourcebot-dev/sourcebot/pull/1405)
- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Missing PR link in CHANGELOG entry.

Unlike the surrounding entries, this new line has no trailing [#<id>](url) link. As per coding guidelines, "Update CHANGELOG.md with an entry under [Unreleased] linking to the new PR" and "CHANGELOG.md entries must follow the format: single sentence description followed by a link in the format [#<id>](https://github.com/sourcebot-dev/sourcebot/pull/<id>)."

📝 Proposed fix
-- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.+- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI. [`#1423`](https://github.com/sourcebot-dev/sourcebot/pull/1423)
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
-[EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.
-[EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.[`#1423`](https://github.com/sourcebot-dev/sourcebot/pull/1423)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@CHANGELOG.md` at line 35, The new CHANGELOG.md entry under [Unreleased] is
missing the required pull request link. Update the entry so the single-sentence
description is followed by the matching
[#<id>](https://github.com/sourcebot-dev/sourcebot/pull/<id>) link, consistent
with the surrounding CHANGELOG entries and the project’s CHANGELOG formatting
rules.

Source: Coding guidelines


## [5.0.4] - 2026-06-18

Expand Down
56 changes: 56 additions & 0 deletions packages/web/src/ee/features/chat/agent.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -265,6 +265,62 @@ beforeEach(() => {
});

describe('createMessageStream approval continuation', () => {
test('streams raw MCP tool names for client display', async () => {
const { getConnectedMcpClients } = await import('@/ee/features/chat/mcp/mcpClientFactory');
const { getMcpTools } = await import('@/ee/features/chat/mcp/mcpToolSets');
vi.mocked(getConnectedMcpClients).mockResolvedValueOnce([
{ serverId: 'server-backstage', serverName: 'Backstage' },
] as never);
vi.mocked(getMcpTools).mockResolvedValueOnce({
tools: {},
failedServers: [],
serverFaviconUrls: {
backstage: 'https://backstage.example.com/favicon.ico',
},
toolDisplayNames: {
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
},
cleanup: vi.fn(),
});
mockAi.streamText.mockReturnValue(createFakeStreamResult());

await createMessageStream({
chatId: 'chat-id',
messages: [createUserMessage()],
selectedRepos: [],
disabledMcpServerIds: [],
prisma: {},
model: {},
modelName: 'test-model',
promptCacheStrategy: noopStrategy,
onFinish: vi.fn(),
onError: () => 'error',
userId: 'user-id',
orgId: 1,
} as unknown as Parameters<typeof createMessageStream>[0]);

const execute = mockAi.latestCreateUIMessageStreamOptions?.execute;
if (!execute) {
throw new Error('Expected createUIMessageStream to capture execute callback.');
}

const write = vi.fn();
await execute({
writer: {
merge: vi.fn(),
write,
},
});

expect(write).toHaveBeenCalledWith({
type: 'data-mcp-tool',
data: {
modelToolName: 'mcp_backstage__catalog_query-catalog-entities',
rawToolName: 'catalog.query-catalog-entities',
},
});
});

test.each([
['dynamic', dynamicApprovalRespondedPart],
['static', staticApprovalRespondedPart],
Expand Down
13 changes: 12 additions & 1 deletion packages/web/src/ee/features/chat/agent.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -369,6 +369,12 @@ export const createMessageStream = async ({
data: { sanitizedName, faviconUrl },
});
},
onMcpToolDiscovered: (modelToolName, rawToolName) => {
writer.write({
type: 'data-mcp-tool',
data: { modelToolName, rawToolName },
});
},
onMcpServerFailed: (serverName) => {
writer.write({
type: 'data-mcp-failed-server',
Expand DownExpand Up@@ -501,6 +507,7 @@ interface AgentOptions {
inputSources: Source[];
onWriteSource: (source: Source) => void;
onMcpServerDiscovered: (sanitizedName: string, faviconUrl: string) => void;
onMcpToolDiscovered: (modelToolName: string, rawToolName: string) => void;
onMcpServerFailed: (serverName: string) => void;
traceId: string;
chatId: string;
Expand All@@ -520,6 +527,7 @@ const createAgentStream = async ({
disabledMcpServerIds,
onWriteSource,
onMcpServerDiscovered,
onMcpToolDiscovered,
onMcpServerFailed,
traceId,
chatId,
Expand DownExpand Up@@ -556,7 +564,7 @@ const createAgentStream = async ({
}))
).filter((source) => source !== undefined);

let mcpToolSetsObj: McpToolsResult = { tools: {}, failedServers: [], serverFaviconUrls: {}, cleanup: async () => {} };
let mcpToolSetsObj: McpToolsResult = { tools: {}, failedServers: [], serverFaviconUrls: {}, toolDisplayNames: {}, cleanup: async () => {} };
if (userId && orgId && await hasEntitlement('ask') && disabledMcpServerIds !== undefined) {
try {
const allMcpClients = await getConnectedMcpClients(prisma, userId, orgId);
Expand All@@ -570,6 +578,9 @@ const createAgentStream = async ({
for (const [sanitizedName, faviconUrl] of Object.entries(mcpToolSetsObj.serverFaviconUrls)) {
onMcpServerDiscovered(sanitizedName, faviconUrl);
}
for (const [modelToolName, rawToolName] of Object.entries(mcpToolSetsObj.toolDisplayNames)) {
onMcpToolDiscovered(modelToolName, rawToolName);
}

if (mcpClients.length > 0) {
logger.info(`Connected to ${mcpClients.length} external MCP server(s): ${mcpClients.map(c => c.serverName).join(', ')}`);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ import { duplicateChat } from '@/features/chat/actions';
import { generateAndUpdateChatNameFromMessage } from '@/ee/features/chat/actions';
import { isServiceError } from '@/lib/utils';
import { NotConfiguredErrorBanner } from '@/features/chat/components/notConfiguredErrorBanner';
import { McpServerIconContext, McpServerIconMap} from '../../mcpServerIconContext';
import { McpServerIconContext, McpServerIconMap, McpToolNameContext, McpToolNameMap } from '../../mcpDisplayMetadataContext';
import { ToolApprovalProvider } from '../../toolApprovalContext';
import useCaptureEvent from '@/hooks/useCaptureEvent';
import { SignInPromptBanner } from './signInPromptBanner';
Expand DownExpand Up@@ -107,6 +107,18 @@ export const ChatThread = ({
return map;
});

const [mcpToolNameMap, setMcpToolNameMap] = useState<McpToolNameMap>(() => {
const map: McpToolNameMap = {};
initialMessages?.forEach((message) => {
message.parts
.filter((part) => part.type === 'data-mcp-tool')
.forEach((part) => {
map[part.data.modelToolName] = part.data.rawToolName;
});
});
return map;
});

const [failedMcpServers, setFailedMcpServers] = useState<string[]>(() => {
const names: string[] = [];
initialMessages?.forEach((message) => {
Expand DownExpand Up@@ -176,6 +188,12 @@ export const ChatThread = ({
[dataPart.data.sanitizedName]: dataPart.data.faviconUrl,
}));
}
if (dataPart.type === 'data-mcp-tool') {
setMcpToolNameMap((prev) => ({
...prev,
[dataPart.data.modelToolName]: dataPart.data.rawToolName,
}));
}
if (dataPart.type === 'data-mcp-failed-server') {
setFailedMcpServers((prev) => {
if (prev.includes(dataPart.data.serverName)) {
Expand DownExpand Up@@ -378,6 +396,7 @@ export const ChatThread = ({
return (
<ToolApprovalProvider value={addToolApprovalResponse}>
<McpServerIconContext.Provider value={mcpServerIconMap}>
<McpToolNameContext.Provider value={mcpToolNameMap}>
<ChatPaneDropzone
className="flex flex-col flex-1 min-h-0 w-full"
onFilesDropped={(files) => chatBoxRef.current?.addFiles(files)}
Expand DownExpand Up@@ -526,6 +545,7 @@ export const ChatThread = ({
)}
</div>
</ChatPaneDropzone>
</McpToolNameContext.Provider>
</McpServerIconContext.Provider>
</ToolApprovalProvider>
);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -546,6 +546,7 @@ export const StepPartRenderer = ({ part, toolTokenUsageMap }: { part: SBChatMess
case 'data-source':
case 'data-command':
case 'data-mcp-server':
case 'data-mcp-tool':
case 'data-mcp-failed-server':
case 'data-attachment':
case 'file':
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,14 @@

import { Button } from "@/components/ui/button";
import { McpFavicon } from "@/ee/features/chat/mcp/components/mcpFavicon";
import { useMcpServerIconMap} from "@/ee/features/chat/mcpServerIconContext";
import { McpToolNameMap, useMcpServerIconMap, useMcpToolNameMap } from "@/ee/features/chat/mcpDisplayMetadataContext";
import { useToolApproval } from "@/ee/features/chat/toolApprovalContext";
import { SBChatToolPart } from "@/features/chat/utils";
import { cn } from "@/lib/utils";
import { getToolName } from "ai";
import { ChevronRight } from "lucide-react";
import { useCallback, useState } from "react";
import { parseMcpToolName } from "./tools/mcpToolComponent";
import { getMcpToolDisplayParts } from "./tools/mcpToolComponent";
import { JsonHighlighter } from "./tools/jsonHighlighter";

export type ApprovalRequestedToolPart = SBChatToolPart & {
Expand All@@ -23,6 +23,7 @@ interface ToolApprovalBannerProps {
export const ToolApprovalBanner = ({ parts }: ToolApprovalBannerProps) => {
const addToolApprovalResponse = useToolApproval();
const iconMap = useMcpServerIconMap();
const rawToolNames = useMcpToolNameMap();

if (parts.length === 0) {
return null;
Expand All@@ -36,6 +37,7 @@ export const ToolApprovalBanner = ({ parts }: ToolApprovalBannerProps) => {
part={part}
addToolApprovalResponse={addToolApprovalResponse}
iconMap={iconMap}
rawToolNames={rawToolNames}
/>
))}
</div>
Expand All@@ -46,17 +48,17 @@ const ToolApprovalItem = ({
part,
addToolApprovalResponse,
iconMap,
rawToolNames,
}: {
part: ApprovalRequestedToolPart;
addToolApprovalResponse: ReturnType<typeof useToolApproval>;
iconMap: Record<string, string | undefined>;
rawToolNames: McpToolNameMap;
}) => {
const [isExpanded, setIsExpanded] = useState(false);
const partToolName = getToolName(part);
const parsed = parseMcpToolName(partToolName);
const serverName = parsed?.serverName ?? partToolName;
const toolName = parsed?.toolName ?? partToolName;
const faviconUrl = parsed ? iconMap[parsed.serverName] : undefined;
const display = getMcpToolDisplayParts(partToolName, rawToolNames);
const faviconUrl = display.serverName ? iconMap[display.serverName] : undefined;

const requestText = JSON.stringify(part.input, null, 2);

Expand All@@ -83,13 +85,13 @@ const ToolApprovalItem = ({
>
<McpFavicon faviconUrl={faviconUrl} className="w-4 h-4" />
<span className="text-sm text-foreground truncate">
{parsed ? (
{display.serverName ? (
<>
Agent wants to use <span className="font-medium">{toolName}</span> from <span className="font-medium">{serverName}</span>
Agent wants to use <span className="font-medium">{display.toolName}</span> from <span className="font-medium">{display.serverName}</span>
</>
) : (
<>
Agent wants to use <span className="font-medium">{toolName}</span>
Agent wants to use <span className="font-medium">{display.toolName}</span>
</>
)}
</span>
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
import { render, screen } from '@testing-library/react';
import type { DynamicToolUIPart } from 'ai';
import { describe, expect, test } from 'vitest';
import { McpToolNameContext } from '@/ee/features/chat/mcpDisplayMetadataContext';
import { getMcpToolDisplayParts, McpToolComponent } from './mcpToolComponent';

describe('getMcpToolDisplayParts', () => {
test('maps provider-safe MCP tool names back to raw tool names for display', () => {
expect(getMcpToolDisplayParts(
'mcp_backstage__catalog_query-catalog-entities',
{
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
},
)).toEqual({
serverName: 'backstage',
toolName: 'catalog.query-catalog-entities',
displayName: 'backstage: catalog.query-catalog-entities',
});
});

test('falls back to the provider-safe name for older messages without metadata', () => {
expect(getMcpToolDisplayParts('mcp_backstage__catalog_query-catalog-entities')).toEqual({
serverName: 'backstage',
toolName: 'catalog_query-catalog-entities',
displayName: 'backstage: catalog_query-catalog-entities',
});
});
});

describe('McpToolComponent', () => {
test('renders the raw MCP tool name when display metadata is available', () => {
const part = {
type: 'dynamic-tool',
toolName: 'mcp_backstage__catalog_query-catalog-entities',
toolCallId: 'tool-call-1',
state: 'approval-requested',
input: { filter: 'kind=component' },
} as DynamicToolUIPart;

render(
<McpToolNameContext.Provider value={{
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
}}>
<McpToolComponent part={part} />
</McpToolNameContext.Provider>
);

expect(screen.getByText('backstage: catalog.query-catalog-entities')).toBeTruthy();
expect(screen.getByText('Request (backstage: catalog.query-catalog-entities)')).toBeTruthy();
expect(screen.queryByText('backstage: catalog_query-catalog-entities')).toBeNull();
});
});
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,6 +39,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Upgraded `@opentelemetry/core` to `^2.8.0`. [#1413](https://github.com/sourcebot-dev/sourcebot/pull/1413)
- [EE] Fixed connector setup dialogs to add scrolling when connector setup content goes out of view.
- Fixed Gitea sync failing with `ERR_STREAM_PREMATURE_CLOSE` by forcing identity encoding on the Gitea API fetch and guarding against null repository responses. [#1405](https://github.com/sourcebot-dev/sourcebot/pull/1405)
- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Missing PR link in CHANGELOG entry.

Unlike the surrounding entries, this new line has no trailing [#<id>](url) link. As per coding guidelines, "Update CHANGELOG.md with an entry under [Unreleased] linking to the new PR" and "CHANGELOG.md entries must follow the format: single sentence description followed by a link in the format [#<id>](https://github.com/sourcebot-dev/sourcebot/pull/<id>)."

📝 Proposed fix
-- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.+- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI. [`#1423`](https://github.com/sourcebot-dev/sourcebot/pull/1423)
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
-[EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.
-[EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.[`#1423`](https://github.com/sourcebot-dev/sourcebot/pull/1423)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@CHANGELOG.md` at line 35, The new CHANGELOG.md entry under [Unreleased] is
missing the required pull request link. Update the entry so the single-sentence
description is followed by the matching
[#<id>](https://github.com/sourcebot-dev/sourcebot/pull/<id>) link, consistent
with the surrounding CHANGELOG entries and the project’s CHANGELOG formatting
rules.

Source: Coding guidelines


## [5.0.4] - 2026-06-18

Expand Down
56 changes: 56 additions & 0 deletions packages/web/src/ee/features/chat/agent.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -265,6 +265,62 @@ beforeEach(() => {
});

describe('createMessageStream approval continuation', () => {
test('streams raw MCP tool names for client display', async () => {
const { getConnectedMcpClients } = await import('@/ee/features/chat/mcp/mcpClientFactory');
const { getMcpTools } = await import('@/ee/features/chat/mcp/mcpToolSets');
vi.mocked(getConnectedMcpClients).mockResolvedValueOnce([
{ serverId: 'server-backstage', serverName: 'Backstage' },
] as never);
vi.mocked(getMcpTools).mockResolvedValueOnce({
tools: {},
failedServers: [],
serverFaviconUrls: {
backstage: 'https://backstage.example.com/favicon.ico',
},
toolDisplayNames: {
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
},
cleanup: vi.fn(),
});
mockAi.streamText.mockReturnValue(createFakeStreamResult());

await createMessageStream({
chatId: 'chat-id',
messages: [createUserMessage()],
selectedRepos: [],
disabledMcpServerIds: [],
prisma: {},
model: {},
modelName: 'test-model',
promptCacheStrategy: noopStrategy,
onFinish: vi.fn(),
onError: () => 'error',
userId: 'user-id',
orgId: 1,
} as unknown as Parameters<typeof createMessageStream>[0]);

const execute = mockAi.latestCreateUIMessageStreamOptions?.execute;
if (!execute) {
throw new Error('Expected createUIMessageStream to capture execute callback.');
}

const write = vi.fn();
await execute({
writer: {
merge: vi.fn(),
write,
},
});

expect(write).toHaveBeenCalledWith({
type: 'data-mcp-tool',
data: {
modelToolName: 'mcp_backstage__catalog_query-catalog-entities',
rawToolName: 'catalog.query-catalog-entities',
},
});
});

test.each([
['dynamic', dynamicApprovalRespondedPart],
['static', staticApprovalRespondedPart],
Expand Down
13 changes: 12 additions & 1 deletion packages/web/src/ee/features/chat/agent.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -369,6 +369,12 @@ export const createMessageStream = async ({
data: { sanitizedName, faviconUrl },
});
},
onMcpToolDiscovered: (modelToolName, rawToolName) => {
writer.write({
type: 'data-mcp-tool',
data: { modelToolName, rawToolName },
});
},
onMcpServerFailed: (serverName) => {
writer.write({
type: 'data-mcp-failed-server',
Expand DownExpand Up@@ -501,6 +507,7 @@ interface AgentOptions {
inputSources: Source[];
onWriteSource: (source: Source) => void;
onMcpServerDiscovered: (sanitizedName: string, faviconUrl: string) => void;
onMcpToolDiscovered: (modelToolName: string, rawToolName: string) => void;
onMcpServerFailed: (serverName: string) => void;
traceId: string;
chatId: string;
Expand All@@ -520,6 +527,7 @@ const createAgentStream = async ({
disabledMcpServerIds,
onWriteSource,
onMcpServerDiscovered,
onMcpToolDiscovered,
onMcpServerFailed,
traceId,
chatId,
Expand DownExpand Up@@ -556,7 +564,7 @@ const createAgentStream = async ({
}))
).filter((source) => source !== undefined);

let mcpToolSetsObj: McpToolsResult = { tools: {}, failedServers: [], serverFaviconUrls: {}, cleanup: async () => {} };
let mcpToolSetsObj: McpToolsResult = { tools: {}, failedServers: [], serverFaviconUrls: {}, toolDisplayNames: {}, cleanup: async () => {} };
if (userId && orgId && await hasEntitlement('ask') && disabledMcpServerIds !== undefined) {
try {
const allMcpClients = await getConnectedMcpClients(prisma, userId, orgId);
Expand All@@ -570,6 +578,9 @@ const createAgentStream = async ({
for (const [sanitizedName, faviconUrl] of Object.entries(mcpToolSetsObj.serverFaviconUrls)) {
onMcpServerDiscovered(sanitizedName, faviconUrl);
}
for (const [modelToolName, rawToolName] of Object.entries(mcpToolSetsObj.toolDisplayNames)) {
onMcpToolDiscovered(modelToolName, rawToolName);
}

if (mcpClients.length > 0) {
logger.info(`Connected to ${mcpClients.length} external MCP server(s): ${mcpClients.map(c => c.serverName).join(', ')}`);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ import { duplicateChat } from '@/features/chat/actions';
import { generateAndUpdateChatNameFromMessage } from '@/ee/features/chat/actions';
import { isServiceError } from '@/lib/utils';
import { NotConfiguredErrorBanner } from '@/features/chat/components/notConfiguredErrorBanner';
import { McpServerIconContext, McpServerIconMap} from '../../mcpServerIconContext';
import { McpServerIconContext, McpServerIconMap, McpToolNameContext, McpToolNameMap } from '../../mcpDisplayMetadataContext';
import { ToolApprovalProvider } from '../../toolApprovalContext';
import useCaptureEvent from '@/hooks/useCaptureEvent';
import { SignInPromptBanner } from './signInPromptBanner';
Expand DownExpand Up@@ -107,6 +107,18 @@ export const ChatThread = ({
return map;
});

const [mcpToolNameMap, setMcpToolNameMap] = useState<McpToolNameMap>(() => {
const map: McpToolNameMap = {};
initialMessages?.forEach((message) => {
message.parts
.filter((part) => part.type === 'data-mcp-tool')
.forEach((part) => {
map[part.data.modelToolName] = part.data.rawToolName;
});
});
return map;
});

const [failedMcpServers, setFailedMcpServers] = useState<string[]>(() => {
const names: string[] = [];
initialMessages?.forEach((message) => {
Expand DownExpand Up@@ -176,6 +188,12 @@ export const ChatThread = ({
[dataPart.data.sanitizedName]: dataPart.data.faviconUrl,
}));
}
if (dataPart.type === 'data-mcp-tool') {
setMcpToolNameMap((prev) => ({
...prev,
[dataPart.data.modelToolName]: dataPart.data.rawToolName,
}));
}
if (dataPart.type === 'data-mcp-failed-server') {
setFailedMcpServers((prev) => {
if (prev.includes(dataPart.data.serverName)) {
Expand DownExpand Up@@ -378,6 +396,7 @@ export const ChatThread = ({
return (
<ToolApprovalProvider value={addToolApprovalResponse}>
<McpServerIconContext.Provider value={mcpServerIconMap}>
<McpToolNameContext.Provider value={mcpToolNameMap}>
<ChatPaneDropzone
className="flex flex-col flex-1 min-h-0 w-full"
onFilesDropped={(files) => chatBoxRef.current?.addFiles(files)}
Expand DownExpand Up@@ -526,6 +545,7 @@ export const ChatThread = ({
)}
</div>
</ChatPaneDropzone>
</McpToolNameContext.Provider>
</McpServerIconContext.Provider>
</ToolApprovalProvider>
);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -546,6 +546,7 @@ export const StepPartRenderer = ({ part, toolTokenUsageMap }: { part: SBChatMess
case 'data-source':
case 'data-command':
case 'data-mcp-server':
case 'data-mcp-tool':
case 'data-mcp-failed-server':
case 'data-attachment':
case 'file':
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,14 @@

import { Button } from "@/components/ui/button";
import { McpFavicon } from "@/ee/features/chat/mcp/components/mcpFavicon";
import { useMcpServerIconMap} from "@/ee/features/chat/mcpServerIconContext";
import { McpToolNameMap, useMcpServerIconMap, useMcpToolNameMap } from "@/ee/features/chat/mcpDisplayMetadataContext";
import { useToolApproval } from "@/ee/features/chat/toolApprovalContext";
import { SBChatToolPart } from "@/features/chat/utils";
import { cn } from "@/lib/utils";
import { getToolName } from "ai";
import { ChevronRight } from "lucide-react";
import { useCallback, useState } from "react";
import { parseMcpToolName } from "./tools/mcpToolComponent";
import { getMcpToolDisplayParts } from "./tools/mcpToolComponent";
import { JsonHighlighter } from "./tools/jsonHighlighter";

export type ApprovalRequestedToolPart = SBChatToolPart & {
Expand All@@ -23,6 +23,7 @@ interface ToolApprovalBannerProps {
export const ToolApprovalBanner = ({ parts }: ToolApprovalBannerProps) => {
const addToolApprovalResponse = useToolApproval();
const iconMap = useMcpServerIconMap();
const rawToolNames = useMcpToolNameMap();

if (parts.length === 0) {
return null;
Expand All@@ -36,6 +37,7 @@ export const ToolApprovalBanner = ({ parts }: ToolApprovalBannerProps) => {
part={part}
addToolApprovalResponse={addToolApprovalResponse}
iconMap={iconMap}
rawToolNames={rawToolNames}
/>
))}
</div>
Expand All@@ -46,17 +48,17 @@ const ToolApprovalItem = ({
part,
addToolApprovalResponse,
iconMap,
rawToolNames,
}: {
part: ApprovalRequestedToolPart;
addToolApprovalResponse: ReturnType<typeof useToolApproval>;
iconMap: Record<string, string | undefined>;
rawToolNames: McpToolNameMap;
}) => {
const [isExpanded, setIsExpanded] = useState(false);
const partToolName = getToolName(part);
const parsed = parseMcpToolName(partToolName);
const serverName = parsed?.serverName ?? partToolName;
const toolName = parsed?.toolName ?? partToolName;
const faviconUrl = parsed ? iconMap[parsed.serverName] : undefined;
const display = getMcpToolDisplayParts(partToolName, rawToolNames);
const faviconUrl = display.serverName ? iconMap[display.serverName] : undefined;

const requestText = JSON.stringify(part.input, null, 2);

Expand All@@ -83,13 +85,13 @@ const ToolApprovalItem = ({
>
<McpFavicon faviconUrl={faviconUrl} className="w-4 h-4" />
<span className="text-sm text-foreground truncate">
{parsed ? (
{display.serverName ? (
<>
Agent wants to use <span className="font-medium">{toolName}</span> from <span className="font-medium">{serverName}</span>
Agent wants to use <span className="font-medium">{display.toolName}</span> from <span className="font-medium">{display.serverName}</span>
</>
) : (
<>
Agent wants to use <span className="font-medium">{toolName}</span>
Agent wants to use <span className="font-medium">{display.toolName}</span>
</>
)}
</span>
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
import { render, screen } from '@testing-library/react';
import type { DynamicToolUIPart } from 'ai';
import { describe, expect, test } from 'vitest';
import { McpToolNameContext } from '@/ee/features/chat/mcpDisplayMetadataContext';
import { getMcpToolDisplayParts, McpToolComponent } from './mcpToolComponent';

describe('getMcpToolDisplayParts', () => {
test('maps provider-safe MCP tool names back to raw tool names for display', () => {
expect(getMcpToolDisplayParts(
'mcp_backstage__catalog_query-catalog-entities',
{
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
},
)).toEqual({
serverName: 'backstage',
toolName: 'catalog.query-catalog-entities',
displayName: 'backstage: catalog.query-catalog-entities',
});
});

test('falls back to the provider-safe name for older messages without metadata', () => {
expect(getMcpToolDisplayParts('mcp_backstage__catalog_query-catalog-entities')).toEqual({
serverName: 'backstage',
toolName: 'catalog_query-catalog-entities',
displayName: 'backstage: catalog_query-catalog-entities',
});
});
});

describe('McpToolComponent', () => {
test('renders the raw MCP tool name when display metadata is available', () => {
const part = {
type: 'dynamic-tool',
toolName: 'mcp_backstage__catalog_query-catalog-entities',
toolCallId: 'tool-call-1',
state: 'approval-requested',
input: { filter: 'kind=component' },
} as DynamicToolUIPart;

render(
<McpToolNameContext.Provider value={{
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
}}>
<McpToolComponent part={part} />
</McpToolNameContext.Provider>
);

expect(screen.getByText('backstage: catalog.query-catalog-entities')).toBeTruthy();
expect(screen.getByText('Request (backstage: catalog.query-catalog-entities)')).toBeTruthy();
expect(screen.queryByText('backstage: catalog_query-catalog-entities')).toBeNull();
});
});
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length \u003e 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,6 +39,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Upgraded `@opentelemetry/core` to `^2.8.0`. [#1413](https://github.com/sourcebot-dev/sourcebot/pull/1413)
- [EE] Fixed connector setup dialogs to add scrolling when connector setup content goes out of view.
- Fixed Gitea sync failing with `ERR_STREAM_PREMATURE_CLOSE` by forcing identity encoding on the Gitea API fetch and guarding against null repository responses. [#1405](https://github.com/sourcebot-dev/sourcebot/pull/1405)
- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Missing PR link in CHANGELOG entry.

Unlike the surrounding entries, this new line has no trailing [#<id>](url) link. As per coding guidelines, "Update CHANGELOG.md with an entry under [Unreleased] linking to the new PR" and "CHANGELOG.md entries must follow the format: single sentence description followed by a link in the format [#<id>](https://github.com/sourcebot-dev/sourcebot/pull/<id>)."

📝 Proposed fix
-- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.+- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI. [`#1423`](https://github.com/sourcebot-dev/sourcebot/pull/1423)
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
-[EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.
-[EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.[`#1423`](https://github.com/sourcebot-dev/sourcebot/pull/1423)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@CHANGELOG.md` at line 35, The new CHANGELOG.md entry under [Unreleased] is
missing the required pull request link. Update the entry so the single-sentence
description is followed by the matching
[#<id>](https://github.com/sourcebot-dev/sourcebot/pull/<id>) link, consistent
with the surrounding CHANGELOG entries and the project’s CHANGELOG formatting
rules.

Source: Coding guidelines


## [5.0.4] - 2026-06-18

Expand Down
56 changes: 56 additions & 0 deletions packages/web/src/ee/features/chat/agent.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -265,6 +265,62 @@ beforeEach(() => {
});

describe('createMessageStream approval continuation', () => {
test('streams raw MCP tool names for client display', async () => {
const { getConnectedMcpClients } = await import('@/ee/features/chat/mcp/mcpClientFactory');
const { getMcpTools } = await import('@/ee/features/chat/mcp/mcpToolSets');
vi.mocked(getConnectedMcpClients).mockResolvedValueOnce([
{ serverId: 'server-backstage', serverName: 'Backstage' },
] as never);
vi.mocked(getMcpTools).mockResolvedValueOnce({
tools: {},
failedServers: [],
serverFaviconUrls: {
backstage: 'https://backstage.example.com/favicon.ico',
},
toolDisplayNames: {
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
},
cleanup: vi.fn(),
});
mockAi.streamText.mockReturnValue(createFakeStreamResult());

await createMessageStream({
chatId: 'chat-id',
messages: [createUserMessage()],
selectedRepos: [],
disabledMcpServerIds: [],
prisma: {},
model: {},
modelName: 'test-model',
promptCacheStrategy: noopStrategy,
onFinish: vi.fn(),
onError: () => 'error',
userId: 'user-id',
orgId: 1,
} as unknown as Parameters<typeof createMessageStream>[0]);

const execute = mockAi.latestCreateUIMessageStreamOptions?.execute;
if (!execute) {
throw new Error('Expected createUIMessageStream to capture execute callback.');
}

const write = vi.fn();
await execute({
writer: {
merge: vi.fn(),
write,
},
});

expect(write).toHaveBeenCalledWith({
type: 'data-mcp-tool',
data: {
modelToolName: 'mcp_backstage__catalog_query-catalog-entities',
rawToolName: 'catalog.query-catalog-entities',
},
});
});

test.each([
['dynamic', dynamicApprovalRespondedPart],
['static', staticApprovalRespondedPart],
Expand Down
13 changes: 12 additions & 1 deletion packages/web/src/ee/features/chat/agent.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -369,6 +369,12 @@ export const createMessageStream = async ({
data: { sanitizedName, faviconUrl },
});
},
onMcpToolDiscovered: (modelToolName, rawToolName) => {
writer.write({
type: 'data-mcp-tool',
data: { modelToolName, rawToolName },
});
},
onMcpServerFailed: (serverName) => {
writer.write({
type: 'data-mcp-failed-server',
Expand DownExpand Up@@ -501,6 +507,7 @@ interface AgentOptions {
inputSources: Source[];
onWriteSource: (source: Source) => void;
onMcpServerDiscovered: (sanitizedName: string, faviconUrl: string) => void;
onMcpToolDiscovered: (modelToolName: string, rawToolName: string) => void;
onMcpServerFailed: (serverName: string) => void;
traceId: string;
chatId: string;
Expand All@@ -520,6 +527,7 @@ const createAgentStream = async ({
disabledMcpServerIds,
onWriteSource,
onMcpServerDiscovered,
onMcpToolDiscovered,
onMcpServerFailed,
traceId,
chatId,
Expand DownExpand Up@@ -556,7 +564,7 @@ const createAgentStream = async ({
}))
).filter((source) => source !== undefined);

let mcpToolSetsObj: McpToolsResult = { tools: {}, failedServers: [], serverFaviconUrls: {}, cleanup: async () => {} };
let mcpToolSetsObj: McpToolsResult = { tools: {}, failedServers: [], serverFaviconUrls: {}, toolDisplayNames: {}, cleanup: async () => {} };
if (userId && orgId && await hasEntitlement('ask') && disabledMcpServerIds !== undefined) {
try {
const allMcpClients = await getConnectedMcpClients(prisma, userId, orgId);
Expand All@@ -570,6 +578,9 @@ const createAgentStream = async ({
for (const [sanitizedName, faviconUrl] of Object.entries(mcpToolSetsObj.serverFaviconUrls)) {
onMcpServerDiscovered(sanitizedName, faviconUrl);
}
for (const [modelToolName, rawToolName] of Object.entries(mcpToolSetsObj.toolDisplayNames)) {
onMcpToolDiscovered(modelToolName, rawToolName);
}

if (mcpClients.length > 0) {
logger.info(`Connected to ${mcpClients.length} external MCP server(s): ${mcpClients.map(c => c.serverName).join(', ')}`);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ import { duplicateChat } from '@/features/chat/actions';
import { generateAndUpdateChatNameFromMessage } from '@/ee/features/chat/actions';
import { isServiceError } from '@/lib/utils';
import { NotConfiguredErrorBanner } from '@/features/chat/components/notConfiguredErrorBanner';
import { McpServerIconContext, McpServerIconMap} from '../../mcpServerIconContext';
import { McpServerIconContext, McpServerIconMap, McpToolNameContext, McpToolNameMap } from '../../mcpDisplayMetadataContext';
import { ToolApprovalProvider } from '../../toolApprovalContext';
import useCaptureEvent from '@/hooks/useCaptureEvent';
import { SignInPromptBanner } from './signInPromptBanner';
Expand DownExpand Up@@ -107,6 +107,18 @@ export const ChatThread = ({
return map;
});

const [mcpToolNameMap, setMcpToolNameMap] = useState<McpToolNameMap>(() => {
const map: McpToolNameMap = {};
initialMessages?.forEach((message) => {
message.parts
.filter((part) => part.type === 'data-mcp-tool')
.forEach((part) => {
map[part.data.modelToolName] = part.data.rawToolName;
});
});
return map;
});

const [failedMcpServers, setFailedMcpServers] = useState<string[]>(() => {
const names: string[] = [];
initialMessages?.forEach((message) => {
Expand DownExpand Up@@ -176,6 +188,12 @@ export const ChatThread = ({
[dataPart.data.sanitizedName]: dataPart.data.faviconUrl,
}));
}
if (dataPart.type === 'data-mcp-tool') {
setMcpToolNameMap((prev) => ({
...prev,
[dataPart.data.modelToolName]: dataPart.data.rawToolName,
}));
}
if (dataPart.type === 'data-mcp-failed-server') {
setFailedMcpServers((prev) => {
if (prev.includes(dataPart.data.serverName)) {
Expand DownExpand Up@@ -378,6 +396,7 @@ export const ChatThread = ({
return (
<ToolApprovalProvider value={addToolApprovalResponse}>
<McpServerIconContext.Provider value={mcpServerIconMap}>
<McpToolNameContext.Provider value={mcpToolNameMap}>
<ChatPaneDropzone
className="flex flex-col flex-1 min-h-0 w-full"
onFilesDropped={(files) => chatBoxRef.current?.addFiles(files)}
Expand DownExpand Up@@ -526,6 +545,7 @@ export const ChatThread = ({
)}
</div>
</ChatPaneDropzone>
</McpToolNameContext.Provider>
</McpServerIconContext.Provider>
</ToolApprovalProvider>
);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -546,6 +546,7 @@ export const StepPartRenderer = ({ part, toolTokenUsageMap }: { part: SBChatMess
case 'data-source':
case 'data-command':
case 'data-mcp-server':
case 'data-mcp-tool':
case 'data-mcp-failed-server':
case 'data-attachment':
case 'file':
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,14 @@

import { Button } from "@/components/ui/button";
import { McpFavicon } from "@/ee/features/chat/mcp/components/mcpFavicon";
import { useMcpServerIconMap} from "@/ee/features/chat/mcpServerIconContext";
import { McpToolNameMap, useMcpServerIconMap, useMcpToolNameMap } from "@/ee/features/chat/mcpDisplayMetadataContext";
import { useToolApproval } from "@/ee/features/chat/toolApprovalContext";
import { SBChatToolPart } from "@/features/chat/utils";
import { cn } from "@/lib/utils";
import { getToolName } from "ai";
import { ChevronRight } from "lucide-react";
import { useCallback, useState } from "react";
import { parseMcpToolName } from "./tools/mcpToolComponent";
import { getMcpToolDisplayParts } from "./tools/mcpToolComponent";
import { JsonHighlighter } from "./tools/jsonHighlighter";

export type ApprovalRequestedToolPart = SBChatToolPart & {
Expand All@@ -23,6 +23,7 @@ interface ToolApprovalBannerProps {
export const ToolApprovalBanner = ({ parts }: ToolApprovalBannerProps) => {
const addToolApprovalResponse = useToolApproval();
const iconMap = useMcpServerIconMap();
const rawToolNames = useMcpToolNameMap();

if (parts.length === 0) {
return null;
Expand All@@ -36,6 +37,7 @@ export const ToolApprovalBanner = ({ parts }: ToolApprovalBannerProps) => {
part={part}
addToolApprovalResponse={addToolApprovalResponse}
iconMap={iconMap}
rawToolNames={rawToolNames}
/>
))}
</div>
Expand All@@ -46,17 +48,17 @@ const ToolApprovalItem = ({
part,
addToolApprovalResponse,
iconMap,
rawToolNames,
}: {
part: ApprovalRequestedToolPart;
addToolApprovalResponse: ReturnType<typeof useToolApproval>;
iconMap: Record<string, string | undefined>;
rawToolNames: McpToolNameMap;
}) => {
const [isExpanded, setIsExpanded] = useState(false);
const partToolName = getToolName(part);
const parsed = parseMcpToolName(partToolName);
const serverName = parsed?.serverName ?? partToolName;
const toolName = parsed?.toolName ?? partToolName;
const faviconUrl = parsed ? iconMap[parsed.serverName] : undefined;
const display = getMcpToolDisplayParts(partToolName, rawToolNames);
const faviconUrl = display.serverName ? iconMap[display.serverName] : undefined;

const requestText = JSON.stringify(part.input, null, 2);

Expand All@@ -83,13 +85,13 @@ const ToolApprovalItem = ({
>
<McpFavicon faviconUrl={faviconUrl} className="w-4 h-4" />
<span className="text-sm text-foreground truncate">
{parsed ? (
{display.serverName ? (
<>
Agent wants to use <span className="font-medium">{toolName}</span> from <span className="font-medium">{serverName}</span>
Agent wants to use <span className="font-medium">{display.toolName}</span> from <span className="font-medium">{display.serverName}</span>
</>
) : (
<>
Agent wants to use <span className="font-medium">{toolName}</span>
Agent wants to use <span className="font-medium">{display.toolName}</span>
</>
)}
</span>
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
import { render, screen } from '@testing-library/react';
import type { DynamicToolUIPart } from 'ai';
import { describe, expect, test } from 'vitest';
import { McpToolNameContext } from '@/ee/features/chat/mcpDisplayMetadataContext';
import { getMcpToolDisplayParts, McpToolComponent } from './mcpToolComponent';

describe('getMcpToolDisplayParts', () => {
test('maps provider-safe MCP tool names back to raw tool names for display', () => {
expect(getMcpToolDisplayParts(
'mcp_backstage__catalog_query-catalog-entities',
{
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
},
)).toEqual({
serverName: 'backstage',
toolName: 'catalog.query-catalog-entities',
displayName: 'backstage: catalog.query-catalog-entities',
});
});

test('falls back to the provider-safe name for older messages without metadata', () => {
expect(getMcpToolDisplayParts('mcp_backstage__catalog_query-catalog-entities')).toEqual({
serverName: 'backstage',
toolName: 'catalog_query-catalog-entities',
displayName: 'backstage: catalog_query-catalog-entities',
});
});
});

describe('McpToolComponent', () => {
test('renders the raw MCP tool name when display metadata is available', () => {
const part = {
type: 'dynamic-tool',
toolName: 'mcp_backstage__catalog_query-catalog-entities',
toolCallId: 'tool-call-1',
state: 'approval-requested',
input: { filter: 'kind=component' },
} as DynamicToolUIPart;

render(
<McpToolNameContext.Provider value={{
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
}}>
<McpToolComponent part={part} />
</McpToolNameContext.Provider>
);

expect(screen.getByText('backstage: catalog.query-catalog-entities')).toBeTruthy();
expect(screen.getByText('Request (backstage: catalog.query-catalog-entities)')).toBeTruthy();
expect(screen.queryByText('backstage: catalog_query-catalog-entities')).toBeNull();
});
});
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,6 +39,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Upgraded `@opentelemetry/core` to `^2.8.0`. [#1413](https://github.com/sourcebot-dev/sourcebot/pull/1413)
- [EE] Fixed connector setup dialogs to add scrolling when connector setup content goes out of view.
- Fixed Gitea sync failing with `ERR_STREAM_PREMATURE_CLOSE` by forcing identity encoding on the Gitea API fetch and guarding against null repository responses. [#1405](https://github.com/sourcebot-dev/sourcebot/pull/1405)
- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Missing PR link in CHANGELOG entry.

Unlike the surrounding entries, this new line has no trailing [#<id>](url) link. As per coding guidelines, "Update CHANGELOG.md with an entry under [Unreleased] linking to the new PR" and "CHANGELOG.md entries must follow the format: single sentence description followed by a link in the format [#<id>](https://github.com/sourcebot-dev/sourcebot/pull/<id>)."

📝 Proposed fix
-- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.+- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI. [`#1423`](https://github.com/sourcebot-dev/sourcebot/pull/1423)
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
-[EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.
-[EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.[`#1423`](https://github.com/sourcebot-dev/sourcebot/pull/1423)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@CHANGELOG.md` at line 35, The new CHANGELOG.md entry under [Unreleased] is
missing the required pull request link. Update the entry so the single-sentence
description is followed by the matching
[#<id>](https://github.com/sourcebot-dev/sourcebot/pull/<id>) link, consistent
with the surrounding CHANGELOG entries and the project’s CHANGELOG formatting
rules.

Source: Coding guidelines


## [5.0.4] - 2026-06-18

Expand Down
56 changes: 56 additions & 0 deletions packages/web/src/ee/features/chat/agent.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -265,6 +265,62 @@ beforeEach(() => {
});

describe('createMessageStream approval continuation', () => {
test('streams raw MCP tool names for client display', async () => {
const { getConnectedMcpClients } = await import('@/ee/features/chat/mcp/mcpClientFactory');
const { getMcpTools } = await import('@/ee/features/chat/mcp/mcpToolSets');
vi.mocked(getConnectedMcpClients).mockResolvedValueOnce([
{ serverId: 'server-backstage', serverName: 'Backstage' },
] as never);
vi.mocked(getMcpTools).mockResolvedValueOnce({
tools: {},
failedServers: [],
serverFaviconUrls: {
backstage: 'https://backstage.example.com/favicon.ico',
},
toolDisplayNames: {
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
},
cleanup: vi.fn(),
});
mockAi.streamText.mockReturnValue(createFakeStreamResult());

await createMessageStream({
chatId: 'chat-id',
messages: [createUserMessage()],
selectedRepos: [],
disabledMcpServerIds: [],
prisma: {},
model: {},
modelName: 'test-model',
promptCacheStrategy: noopStrategy,
onFinish: vi.fn(),
onError: () => 'error',
userId: 'user-id',
orgId: 1,
} as unknown as Parameters<typeof createMessageStream>[0]);

const execute = mockAi.latestCreateUIMessageStreamOptions?.execute;
if (!execute) {
throw new Error('Expected createUIMessageStream to capture execute callback.');
}

const write = vi.fn();
await execute({
writer: {
merge: vi.fn(),
write,
},
});

expect(write).toHaveBeenCalledWith({
type: 'data-mcp-tool',
data: {
modelToolName: 'mcp_backstage__catalog_query-catalog-entities',
rawToolName: 'catalog.query-catalog-entities',
},
});
});

test.each([
['dynamic', dynamicApprovalRespondedPart],
['static', staticApprovalRespondedPart],
Expand Down
13 changes: 12 additions & 1 deletion packages/web/src/ee/features/chat/agent.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -369,6 +369,12 @@ export const createMessageStream = async ({
data: { sanitizedName, faviconUrl },
});
},
onMcpToolDiscovered: (modelToolName, rawToolName) => {
writer.write({
type: 'data-mcp-tool',
data: { modelToolName, rawToolName },
});
},
onMcpServerFailed: (serverName) => {
writer.write({
type: 'data-mcp-failed-server',
Expand DownExpand Up@@ -501,6 +507,7 @@ interface AgentOptions {
inputSources: Source[];
onWriteSource: (source: Source) => void;
onMcpServerDiscovered: (sanitizedName: string, faviconUrl: string) => void;
onMcpToolDiscovered: (modelToolName: string, rawToolName: string) => void;
onMcpServerFailed: (serverName: string) => void;
traceId: string;
chatId: string;
Expand All@@ -520,6 +527,7 @@ const createAgentStream = async ({
disabledMcpServerIds,
onWriteSource,
onMcpServerDiscovered,
onMcpToolDiscovered,
onMcpServerFailed,
traceId,
chatId,
Expand DownExpand Up@@ -556,7 +564,7 @@ const createAgentStream = async ({
}))
).filter((source) => source !== undefined);

let mcpToolSetsObj: McpToolsResult = { tools: {}, failedServers: [], serverFaviconUrls: {}, cleanup: async () => {} };
let mcpToolSetsObj: McpToolsResult = { tools: {}, failedServers: [], serverFaviconUrls: {}, toolDisplayNames: {}, cleanup: async () => {} };
if (userId && orgId && await hasEntitlement('ask') && disabledMcpServerIds !== undefined) {
try {
const allMcpClients = await getConnectedMcpClients(prisma, userId, orgId);
Expand All@@ -570,6 +578,9 @@ const createAgentStream = async ({
for (const [sanitizedName, faviconUrl] of Object.entries(mcpToolSetsObj.serverFaviconUrls)) {
onMcpServerDiscovered(sanitizedName, faviconUrl);
}
for (const [modelToolName, rawToolName] of Object.entries(mcpToolSetsObj.toolDisplayNames)) {
onMcpToolDiscovered(modelToolName, rawToolName);
}

if (mcpClients.length > 0) {
logger.info(`Connected to ${mcpClients.length} external MCP server(s): ${mcpClients.map(c => c.serverName).join(', ')}`);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ import { duplicateChat } from '@/features/chat/actions';
import { generateAndUpdateChatNameFromMessage } from '@/ee/features/chat/actions';
import { isServiceError } from '@/lib/utils';
import { NotConfiguredErrorBanner } from '@/features/chat/components/notConfiguredErrorBanner';
import { McpServerIconContext, McpServerIconMap} from '../../mcpServerIconContext';
import { McpServerIconContext, McpServerIconMap, McpToolNameContext, McpToolNameMap } from '../../mcpDisplayMetadataContext';
import { ToolApprovalProvider } from '../../toolApprovalContext';
import useCaptureEvent from '@/hooks/useCaptureEvent';
import { SignInPromptBanner } from './signInPromptBanner';
Expand DownExpand Up@@ -107,6 +107,18 @@ export const ChatThread = ({
return map;
});

const [mcpToolNameMap, setMcpToolNameMap] = useState<McpToolNameMap>(() => {
const map: McpToolNameMap = {};
initialMessages?.forEach((message) => {
message.parts
.filter((part) => part.type === 'data-mcp-tool')
.forEach((part) => {
map[part.data.modelToolName] = part.data.rawToolName;
});
});
return map;
});

const [failedMcpServers, setFailedMcpServers] = useState<string[]>(() => {
const names: string[] = [];
initialMessages?.forEach((message) => {
Expand DownExpand Up@@ -176,6 +188,12 @@ export const ChatThread = ({
[dataPart.data.sanitizedName]: dataPart.data.faviconUrl,
}));
}
if (dataPart.type === 'data-mcp-tool') {
setMcpToolNameMap((prev) => ({
...prev,
[dataPart.data.modelToolName]: dataPart.data.rawToolName,
}));
}
if (dataPart.type === 'data-mcp-failed-server') {
setFailedMcpServers((prev) => {
if (prev.includes(dataPart.data.serverName)) {
Expand DownExpand Up@@ -378,6 +396,7 @@ export const ChatThread = ({
return (
<ToolApprovalProvider value={addToolApprovalResponse}>
<McpServerIconContext.Provider value={mcpServerIconMap}>
<McpToolNameContext.Provider value={mcpToolNameMap}>
<ChatPaneDropzone
className="flex flex-col flex-1 min-h-0 w-full"
onFilesDropped={(files) => chatBoxRef.current?.addFiles(files)}
Expand DownExpand Up@@ -526,6 +545,7 @@ export const ChatThread = ({
)}
</div>
</ChatPaneDropzone>
</McpToolNameContext.Provider>
</McpServerIconContext.Provider>
</ToolApprovalProvider>
);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -546,6 +546,7 @@ export const StepPartRenderer = ({ part, toolTokenUsageMap }: { part: SBChatMess
case 'data-source':
case 'data-command':
case 'data-mcp-server':
case 'data-mcp-tool':
case 'data-mcp-failed-server':
case 'data-attachment':
case 'file':
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,14 @@

import { Button } from "@/components/ui/button";
import { McpFavicon } from "@/ee/features/chat/mcp/components/mcpFavicon";
import { useMcpServerIconMap} from "@/ee/features/chat/mcpServerIconContext";
import { McpToolNameMap, useMcpServerIconMap, useMcpToolNameMap } from "@/ee/features/chat/mcpDisplayMetadataContext";
import { useToolApproval } from "@/ee/features/chat/toolApprovalContext";
import { SBChatToolPart } from "@/features/chat/utils";
import { cn } from "@/lib/utils";
import { getToolName } from "ai";
import { ChevronRight } from "lucide-react";
import { useCallback, useState } from "react";
import { parseMcpToolName } from "./tools/mcpToolComponent";
import { getMcpToolDisplayParts } from "./tools/mcpToolComponent";
import { JsonHighlighter } from "./tools/jsonHighlighter";

export type ApprovalRequestedToolPart = SBChatToolPart & {
Expand All@@ -23,6 +23,7 @@ interface ToolApprovalBannerProps {
export const ToolApprovalBanner = ({ parts }: ToolApprovalBannerProps) => {
const addToolApprovalResponse = useToolApproval();
const iconMap = useMcpServerIconMap();
const rawToolNames = useMcpToolNameMap();

if (parts.length === 0) {
return null;
Expand All@@ -36,6 +37,7 @@ export const ToolApprovalBanner = ({ parts }: ToolApprovalBannerProps) => {
part={part}
addToolApprovalResponse={addToolApprovalResponse}
iconMap={iconMap}
rawToolNames={rawToolNames}
/>
))}
</div>
Expand All@@ -46,17 +48,17 @@ const ToolApprovalItem = ({
part,
addToolApprovalResponse,
iconMap,
rawToolNames,
}: {
part: ApprovalRequestedToolPart;
addToolApprovalResponse: ReturnType<typeof useToolApproval>;
iconMap: Record<string, string | undefined>;
rawToolNames: McpToolNameMap;
}) => {
const [isExpanded, setIsExpanded] = useState(false);
const partToolName = getToolName(part);
const parsed = parseMcpToolName(partToolName);
const serverName = parsed?.serverName ?? partToolName;
const toolName = parsed?.toolName ?? partToolName;
const faviconUrl = parsed ? iconMap[parsed.serverName] : undefined;
const display = getMcpToolDisplayParts(partToolName, rawToolNames);
const faviconUrl = display.serverName ? iconMap[display.serverName] : undefined;

const requestText = JSON.stringify(part.input, null, 2);

Expand All@@ -83,13 +85,13 @@ const ToolApprovalItem = ({
>
<McpFavicon faviconUrl={faviconUrl} className="w-4 h-4" />
<span className="text-sm text-foreground truncate">
{parsed ? (
{display.serverName ? (
<>
Agent wants to use <span className="font-medium">{toolName}</span> from <span className="font-medium">{serverName}</span>
Agent wants to use <span className="font-medium">{display.toolName}</span> from <span className="font-medium">{display.serverName}</span>
</>
) : (
<>
Agent wants to use <span className="font-medium">{toolName}</span>
Agent wants to use <span className="font-medium">{display.toolName}</span>
</>
)}
</span>
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
import { render, screen } from '@testing-library/react';
import type { DynamicToolUIPart } from 'ai';
import { describe, expect, test } from 'vitest';
import { McpToolNameContext } from '@/ee/features/chat/mcpDisplayMetadataContext';
import { getMcpToolDisplayParts, McpToolComponent } from './mcpToolComponent';

describe('getMcpToolDisplayParts', () => {
test('maps provider-safe MCP tool names back to raw tool names for display', () => {
expect(getMcpToolDisplayParts(
'mcp_backstage__catalog_query-catalog-entities',
{
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
},
)).toEqual({
serverName: 'backstage',
toolName: 'catalog.query-catalog-entities',
displayName: 'backstage: catalog.query-catalog-entities',
});
});

test('falls back to the provider-safe name for older messages without metadata', () => {
expect(getMcpToolDisplayParts('mcp_backstage__catalog_query-catalog-entities')).toEqual({
serverName: 'backstage',
toolName: 'catalog_query-catalog-entities',
displayName: 'backstage: catalog_query-catalog-entities',
});
});
});

describe('McpToolComponent', () => {
test('renders the raw MCP tool name when display metadata is available', () => {
const part = {
type: 'dynamic-tool',
toolName: 'mcp_backstage__catalog_query-catalog-entities',
toolCallId: 'tool-call-1',
state: 'approval-requested',
input: { filter: 'kind=component' },
} as DynamicToolUIPart;

render(
<McpToolNameContext.Provider value={{
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
}}>
<McpToolComponent part={part} />
</McpToolNameContext.Provider>
);

expect(screen.getByText('backstage: catalog.query-catalog-entities')).toBeTruthy();
expect(screen.getByText('Request (backstage: catalog.query-catalog-entities)')).toBeTruthy();
expect(screen.queryByText('backstage: catalog_query-catalog-entities')).toBeNull();
});
});
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,6 +39,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Upgraded `@opentelemetry/core` to `^2.8.0`. [#1413](https://github.com/sourcebot-dev/sourcebot/pull/1413)
- [EE] Fixed connector setup dialogs to add scrolling when connector setup content goes out of view.
- Fixed Gitea sync failing with `ERR_STREAM_PREMATURE_CLOSE` by forcing identity encoding on the Gitea API fetch and guarding against null repository responses. [#1405](https://github.com/sourcebot-dev/sourcebot/pull/1405)
- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Missing PR link in CHANGELOG entry.

Unlike the surrounding entries, this new line has no trailing [#<id>](url) link. As per coding guidelines, "Update CHANGELOG.md with an entry under [Unreleased] linking to the new PR" and "CHANGELOG.md entries must follow the format: single sentence description followed by a link in the format [#<id>](https://github.com/sourcebot-dev/sourcebot/pull/<id>)."

📝 Proposed fix
-- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.+- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI. [`#1423`](https://github.com/sourcebot-dev/sourcebot/pull/1423)
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
-[EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.
-[EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.[`#1423`](https://github.com/sourcebot-dev/sourcebot/pull/1423)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@CHANGELOG.md` at line 35, The new CHANGELOG.md entry under [Unreleased] is
missing the required pull request link. Update the entry so the single-sentence
description is followed by the matching
[#<id>](https://github.com/sourcebot-dev/sourcebot/pull/<id>) link, consistent
with the surrounding CHANGELOG entries and the project’s CHANGELOG formatting
rules.

Source: Coding guidelines


## [5.0.4] - 2026-06-18

Expand Down
56 changes: 56 additions & 0 deletions packages/web/src/ee/features/chat/agent.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -265,6 +265,62 @@ beforeEach(() => {
});

describe('createMessageStream approval continuation', () => {
test('streams raw MCP tool names for client display', async () => {
const { getConnectedMcpClients } = await import('@/ee/features/chat/mcp/mcpClientFactory');
const { getMcpTools } = await import('@/ee/features/chat/mcp/mcpToolSets');
vi.mocked(getConnectedMcpClients).mockResolvedValueOnce([
{ serverId: 'server-backstage', serverName: 'Backstage' },
] as never);
vi.mocked(getMcpTools).mockResolvedValueOnce({
tools: {},
failedServers: [],
serverFaviconUrls: {
backstage: 'https://backstage.example.com/favicon.ico',
},
toolDisplayNames: {
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
},
cleanup: vi.fn(),
});
mockAi.streamText.mockReturnValue(createFakeStreamResult());

await createMessageStream({
chatId: 'chat-id',
messages: [createUserMessage()],
selectedRepos: [],
disabledMcpServerIds: [],
prisma: {},
model: {},
modelName: 'test-model',
promptCacheStrategy: noopStrategy,
onFinish: vi.fn(),
onError: () => 'error',
userId: 'user-id',
orgId: 1,
} as unknown as Parameters<typeof createMessageStream>[0]);

const execute = mockAi.latestCreateUIMessageStreamOptions?.execute;
if (!execute) {
throw new Error('Expected createUIMessageStream to capture execute callback.');
}

const write = vi.fn();
await execute({
writer: {
merge: vi.fn(),
write,
},
});

expect(write).toHaveBeenCalledWith({
type: 'data-mcp-tool',
data: {
modelToolName: 'mcp_backstage__catalog_query-catalog-entities',
rawToolName: 'catalog.query-catalog-entities',
},
});
});

test.each([
['dynamic', dynamicApprovalRespondedPart],
['static', staticApprovalRespondedPart],
Expand Down
13 changes: 12 additions & 1 deletion packages/web/src/ee/features/chat/agent.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -369,6 +369,12 @@ export const createMessageStream = async ({
data: { sanitizedName, faviconUrl },
});
},
onMcpToolDiscovered: (modelToolName, rawToolName) => {
writer.write({
type: 'data-mcp-tool',
data: { modelToolName, rawToolName },
});
},
onMcpServerFailed: (serverName) => {
writer.write({
type: 'data-mcp-failed-server',
Expand DownExpand Up@@ -501,6 +507,7 @@ interface AgentOptions {
inputSources: Source[];
onWriteSource: (source: Source) => void;
onMcpServerDiscovered: (sanitizedName: string, faviconUrl: string) => void;
onMcpToolDiscovered: (modelToolName: string, rawToolName: string) => void;
onMcpServerFailed: (serverName: string) => void;
traceId: string;
chatId: string;
Expand All@@ -520,6 +527,7 @@ const createAgentStream = async ({
disabledMcpServerIds,
onWriteSource,
onMcpServerDiscovered,
onMcpToolDiscovered,
onMcpServerFailed,
traceId,
chatId,
Expand DownExpand Up@@ -556,7 +564,7 @@ const createAgentStream = async ({
}))
).filter((source) => source !== undefined);

let mcpToolSetsObj: McpToolsResult = { tools: {}, failedServers: [], serverFaviconUrls: {}, cleanup: async () => {} };
let mcpToolSetsObj: McpToolsResult = { tools: {}, failedServers: [], serverFaviconUrls: {}, toolDisplayNames: {}, cleanup: async () => {} };
if (userId && orgId && await hasEntitlement('ask') && disabledMcpServerIds !== undefined) {
try {
const allMcpClients = await getConnectedMcpClients(prisma, userId, orgId);
Expand All@@ -570,6 +578,9 @@ const createAgentStream = async ({
for (const [sanitizedName, faviconUrl] of Object.entries(mcpToolSetsObj.serverFaviconUrls)) {
onMcpServerDiscovered(sanitizedName, faviconUrl);
}
for (const [modelToolName, rawToolName] of Object.entries(mcpToolSetsObj.toolDisplayNames)) {
onMcpToolDiscovered(modelToolName, rawToolName);
}

if (mcpClients.length > 0) {
logger.info(`Connected to ${mcpClients.length} external MCP server(s): ${mcpClients.map(c => c.serverName).join(', ')}`);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ import { duplicateChat } from '@/features/chat/actions';
import { generateAndUpdateChatNameFromMessage } from '@/ee/features/chat/actions';
import { isServiceError } from '@/lib/utils';
import { NotConfiguredErrorBanner } from '@/features/chat/components/notConfiguredErrorBanner';
import { McpServerIconContext, McpServerIconMap} from '../../mcpServerIconContext';
import { McpServerIconContext, McpServerIconMap, McpToolNameContext, McpToolNameMap } from '../../mcpDisplayMetadataContext';
import { ToolApprovalProvider } from '../../toolApprovalContext';
import useCaptureEvent from '@/hooks/useCaptureEvent';
import { SignInPromptBanner } from './signInPromptBanner';
Expand DownExpand Up@@ -107,6 +107,18 @@ export const ChatThread = ({
return map;
});

const [mcpToolNameMap, setMcpToolNameMap] = useState<McpToolNameMap>(() => {
const map: McpToolNameMap = {};
initialMessages?.forEach((message) => {
message.parts
.filter((part) => part.type === 'data-mcp-tool')
.forEach((part) => {
map[part.data.modelToolName] = part.data.rawToolName;
});
});
return map;
});

const [failedMcpServers, setFailedMcpServers] = useState<string[]>(() => {
const names: string[] = [];
initialMessages?.forEach((message) => {
Expand DownExpand Up@@ -176,6 +188,12 @@ export const ChatThread = ({
[dataPart.data.sanitizedName]: dataPart.data.faviconUrl,
}));
}
if (dataPart.type === 'data-mcp-tool') {
setMcpToolNameMap((prev) => ({
...prev,
[dataPart.data.modelToolName]: dataPart.data.rawToolName,
}));
}
if (dataPart.type === 'data-mcp-failed-server') {
setFailedMcpServers((prev) => {
if (prev.includes(dataPart.data.serverName)) {
Expand DownExpand Up@@ -378,6 +396,7 @@ export const ChatThread = ({
return (
<ToolApprovalProvider value={addToolApprovalResponse}>
<McpServerIconContext.Provider value={mcpServerIconMap}>
<McpToolNameContext.Provider value={mcpToolNameMap}>
<ChatPaneDropzone
className="flex flex-col flex-1 min-h-0 w-full"
onFilesDropped={(files) => chatBoxRef.current?.addFiles(files)}
Expand DownExpand Up@@ -526,6 +545,7 @@ export const ChatThread = ({
)}
</div>
</ChatPaneDropzone>
</McpToolNameContext.Provider>
</McpServerIconContext.Provider>
</ToolApprovalProvider>
);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -546,6 +546,7 @@ export const StepPartRenderer = ({ part, toolTokenUsageMap }: { part: SBChatMess
case 'data-source':
case 'data-command':
case 'data-mcp-server':
case 'data-mcp-tool':
case 'data-mcp-failed-server':
case 'data-attachment':
case 'file':
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,14 @@

import { Button } from "@/components/ui/button";
import { McpFavicon } from "@/ee/features/chat/mcp/components/mcpFavicon";
import { useMcpServerIconMap} from "@/ee/features/chat/mcpServerIconContext";
import { McpToolNameMap, useMcpServerIconMap, useMcpToolNameMap } from "@/ee/features/chat/mcpDisplayMetadataContext";
import { useToolApproval } from "@/ee/features/chat/toolApprovalContext";
import { SBChatToolPart } from "@/features/chat/utils";
import { cn } from "@/lib/utils";
import { getToolName } from "ai";
import { ChevronRight } from "lucide-react";
import { useCallback, useState } from "react";
import { parseMcpToolName } from "./tools/mcpToolComponent";
import { getMcpToolDisplayParts } from "./tools/mcpToolComponent";
import { JsonHighlighter } from "./tools/jsonHighlighter";

export type ApprovalRequestedToolPart = SBChatToolPart & {
Expand All@@ -23,6 +23,7 @@ interface ToolApprovalBannerProps {
export const ToolApprovalBanner = ({ parts }: ToolApprovalBannerProps) => {
const addToolApprovalResponse = useToolApproval();
const iconMap = useMcpServerIconMap();
const rawToolNames = useMcpToolNameMap();

if (parts.length === 0) {
return null;
Expand All@@ -36,6 +37,7 @@ export const ToolApprovalBanner = ({ parts }: ToolApprovalBannerProps) => {
part={part}
addToolApprovalResponse={addToolApprovalResponse}
iconMap={iconMap}
rawToolNames={rawToolNames}
/>
))}
</div>
Expand All@@ -46,17 +48,17 @@ const ToolApprovalItem = ({
part,
addToolApprovalResponse,
iconMap,
rawToolNames,
}: {
part: ApprovalRequestedToolPart;
addToolApprovalResponse: ReturnType<typeof useToolApproval>;
iconMap: Record<string, string | undefined>;
rawToolNames: McpToolNameMap;
}) => {
const [isExpanded, setIsExpanded] = useState(false);
const partToolName = getToolName(part);
const parsed = parseMcpToolName(partToolName);
const serverName = parsed?.serverName ?? partToolName;
const toolName = parsed?.toolName ?? partToolName;
const faviconUrl = parsed ? iconMap[parsed.serverName] : undefined;
const display = getMcpToolDisplayParts(partToolName, rawToolNames);
const faviconUrl = display.serverName ? iconMap[display.serverName] : undefined;

const requestText = JSON.stringify(part.input, null, 2);

Expand All@@ -83,13 +85,13 @@ const ToolApprovalItem = ({
>
<McpFavicon faviconUrl={faviconUrl} className="w-4 h-4" />
<span className="text-sm text-foreground truncate">
{parsed ? (
{display.serverName ? (
<>
Agent wants to use <span className="font-medium">{toolName}</span> from <span className="font-medium">{serverName}</span>
Agent wants to use <span className="font-medium">{display.toolName}</span> from <span className="font-medium">{display.serverName}</span>
</>
) : (
<>
Agent wants to use <span className="font-medium">{toolName}</span>
Agent wants to use <span className="font-medium">{display.toolName}</span>
</>
)}
</span>
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
import { render, screen } from '@testing-library/react';
import type { DynamicToolUIPart } from 'ai';
import { describe, expect, test } from 'vitest';
import { McpToolNameContext } from '@/ee/features/chat/mcpDisplayMetadataContext';
import { getMcpToolDisplayParts, McpToolComponent } from './mcpToolComponent';

describe('getMcpToolDisplayParts', () => {
test('maps provider-safe MCP tool names back to raw tool names for display', () => {
expect(getMcpToolDisplayParts(
'mcp_backstage__catalog_query-catalog-entities',
{
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
},
)).toEqual({
serverName: 'backstage',
toolName: 'catalog.query-catalog-entities',
displayName: 'backstage: catalog.query-catalog-entities',
});
});

test('falls back to the provider-safe name for older messages without metadata', () => {
expect(getMcpToolDisplayParts('mcp_backstage__catalog_query-catalog-entities')).toEqual({
serverName: 'backstage',
toolName: 'catalog_query-catalog-entities',
displayName: 'backstage: catalog_query-catalog-entities',
});
});
});

describe('McpToolComponent', () => {
test('renders the raw MCP tool name when display metadata is available', () => {
const part = {
type: 'dynamic-tool',
toolName: 'mcp_backstage__catalog_query-catalog-entities',
toolCallId: 'tool-call-1',
state: 'approval-requested',
input: { filter: 'kind=component' },
} as DynamicToolUIPart;

render(
<McpToolNameContext.Provider value={{
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
}}>
<McpToolComponent part={part} />
</McpToolNameContext.Provider>
);

expect(screen.getByText('backstage: catalog.query-catalog-entities')).toBeTruthy();
expect(screen.getByText('Request (backstage: catalog.query-catalog-entities)')).toBeTruthy();
expect(screen.queryByText('backstage: catalog_query-catalog-entities')).toBeNull();
});
});
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,6 +39,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Upgraded `@opentelemetry/core` to `^2.8.0`. [#1413](https://github.com/sourcebot-dev/sourcebot/pull/1413)
- [EE] Fixed connector setup dialogs to add scrolling when connector setup content goes out of view.
- Fixed Gitea sync failing with `ERR_STREAM_PREMATURE_CLOSE` by forcing identity encoding on the Gitea API fetch and guarding against null repository responses. [#1405](https://github.com/sourcebot-dev/sourcebot/pull/1405)
- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Missing PR link in CHANGELOG entry.

Unlike the surrounding entries, this new line has no trailing [#<id>](url) link. As per coding guidelines, "Update CHANGELOG.md with an entry under [Unreleased] linking to the new PR" and "CHANGELOG.md entries must follow the format: single sentence description followed by a link in the format [#<id>](https://github.com/sourcebot-dev/sourcebot/pull/<id>)."

📝 Proposed fix
-- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.+- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI. [`#1423`](https://github.com/sourcebot-dev/sourcebot/pull/1423)
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
-[EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.
-[EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.[`#1423`](https://github.com/sourcebot-dev/sourcebot/pull/1423)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@CHANGELOG.md` at line 35, The new CHANGELOG.md entry under [Unreleased] is
missing the required pull request link. Update the entry so the single-sentence
description is followed by the matching
[#<id>](https://github.com/sourcebot-dev/sourcebot/pull/<id>) link, consistent
with the surrounding CHANGELOG entries and the project’s CHANGELOG formatting
rules.

Source: Coding guidelines


## [5.0.4] - 2026-06-18

Expand Down
56 changes: 56 additions & 0 deletions packages/web/src/ee/features/chat/agent.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -265,6 +265,62 @@ beforeEach(() => {
});

describe('createMessageStream approval continuation', () => {
test('streams raw MCP tool names for client display', async () => {
const { getConnectedMcpClients } = await import('@/ee/features/chat/mcp/mcpClientFactory');
const { getMcpTools } = await import('@/ee/features/chat/mcp/mcpToolSets');
vi.mocked(getConnectedMcpClients).mockResolvedValueOnce([
{ serverId: 'server-backstage', serverName: 'Backstage' },
] as never);
vi.mocked(getMcpTools).mockResolvedValueOnce({
tools: {},
failedServers: [],
serverFaviconUrls: {
backstage: 'https://backstage.example.com/favicon.ico',
},
toolDisplayNames: {
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
},
cleanup: vi.fn(),
});
mockAi.streamText.mockReturnValue(createFakeStreamResult());

await createMessageStream({
chatId: 'chat-id',
messages: [createUserMessage()],
selectedRepos: [],
disabledMcpServerIds: [],
prisma: {},
model: {},
modelName: 'test-model',
promptCacheStrategy: noopStrategy,
onFinish: vi.fn(),
onError: () => 'error',
userId: 'user-id',
orgId: 1,
} as unknown as Parameters<typeof createMessageStream>[0]);

const execute = mockAi.latestCreateUIMessageStreamOptions?.execute;
if (!execute) {
throw new Error('Expected createUIMessageStream to capture execute callback.');
}

const write = vi.fn();
await execute({
writer: {
merge: vi.fn(),
write,
},
});

expect(write).toHaveBeenCalledWith({
type: 'data-mcp-tool',
data: {
modelToolName: 'mcp_backstage__catalog_query-catalog-entities',
rawToolName: 'catalog.query-catalog-entities',
},
});
});

test.each([
['dynamic', dynamicApprovalRespondedPart],
['static', staticApprovalRespondedPart],
Expand Down
13 changes: 12 additions & 1 deletion packages/web/src/ee/features/chat/agent.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -369,6 +369,12 @@ export const createMessageStream = async ({
data: { sanitizedName, faviconUrl },
});
},
onMcpToolDiscovered: (modelToolName, rawToolName) => {
writer.write({
type: 'data-mcp-tool',
data: { modelToolName, rawToolName },
});
},
onMcpServerFailed: (serverName) => {
writer.write({
type: 'data-mcp-failed-server',
Expand DownExpand Up@@ -501,6 +507,7 @@ interface AgentOptions {
inputSources: Source[];
onWriteSource: (source: Source) => void;
onMcpServerDiscovered: (sanitizedName: string, faviconUrl: string) => void;
onMcpToolDiscovered: (modelToolName: string, rawToolName: string) => void;
onMcpServerFailed: (serverName: string) => void;
traceId: string;
chatId: string;
Expand All@@ -520,6 +527,7 @@ const createAgentStream = async ({
disabledMcpServerIds,
onWriteSource,
onMcpServerDiscovered,
onMcpToolDiscovered,
onMcpServerFailed,
traceId,
chatId,
Expand DownExpand Up@@ -556,7 +564,7 @@ const createAgentStream = async ({
}))
).filter((source) => source !== undefined);

let mcpToolSetsObj: McpToolsResult = { tools: {}, failedServers: [], serverFaviconUrls: {}, cleanup: async () => {} };
let mcpToolSetsObj: McpToolsResult = { tools: {}, failedServers: [], serverFaviconUrls: {}, toolDisplayNames: {}, cleanup: async () => {} };
if (userId && orgId && await hasEntitlement('ask') && disabledMcpServerIds !== undefined) {
try {
const allMcpClients = await getConnectedMcpClients(prisma, userId, orgId);
Expand All@@ -570,6 +578,9 @@ const createAgentStream = async ({
for (const [sanitizedName, faviconUrl] of Object.entries(mcpToolSetsObj.serverFaviconUrls)) {
onMcpServerDiscovered(sanitizedName, faviconUrl);
}
for (const [modelToolName, rawToolName] of Object.entries(mcpToolSetsObj.toolDisplayNames)) {
onMcpToolDiscovered(modelToolName, rawToolName);
}

if (mcpClients.length > 0) {
logger.info(`Connected to ${mcpClients.length} external MCP server(s): ${mcpClients.map(c => c.serverName).join(', ')}`);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ import { duplicateChat } from '@/features/chat/actions';
import { generateAndUpdateChatNameFromMessage } from '@/ee/features/chat/actions';
import { isServiceError } from '@/lib/utils';
import { NotConfiguredErrorBanner } from '@/features/chat/components/notConfiguredErrorBanner';
import { McpServerIconContext, McpServerIconMap} from '../../mcpServerIconContext';
import { McpServerIconContext, McpServerIconMap, McpToolNameContext, McpToolNameMap } from '../../mcpDisplayMetadataContext';
import { ToolApprovalProvider } from '../../toolApprovalContext';
import useCaptureEvent from '@/hooks/useCaptureEvent';
import { SignInPromptBanner } from './signInPromptBanner';
Expand DownExpand Up@@ -107,6 +107,18 @@ export const ChatThread = ({
return map;
});

const [mcpToolNameMap, setMcpToolNameMap] = useState<McpToolNameMap>(() => {
const map: McpToolNameMap = {};
initialMessages?.forEach((message) => {
message.parts
.filter((part) => part.type === 'data-mcp-tool')
.forEach((part) => {
map[part.data.modelToolName] = part.data.rawToolName;
});
});
return map;
});

const [failedMcpServers, setFailedMcpServers] = useState<string[]>(() => {
const names: string[] = [];
initialMessages?.forEach((message) => {
Expand DownExpand Up@@ -176,6 +188,12 @@ export const ChatThread = ({
[dataPart.data.sanitizedName]: dataPart.data.faviconUrl,
}));
}
if (dataPart.type === 'data-mcp-tool') {
setMcpToolNameMap((prev) => ({
...prev,
[dataPart.data.modelToolName]: dataPart.data.rawToolName,
}));
}
if (dataPart.type === 'data-mcp-failed-server') {
setFailedMcpServers((prev) => {
if (prev.includes(dataPart.data.serverName)) {
Expand DownExpand Up@@ -378,6 +396,7 @@ export const ChatThread = ({
return (
<ToolApprovalProvider value={addToolApprovalResponse}>
<McpServerIconContext.Provider value={mcpServerIconMap}>
<McpToolNameContext.Provider value={mcpToolNameMap}>
<ChatPaneDropzone
className="flex flex-col flex-1 min-h-0 w-full"
onFilesDropped={(files) => chatBoxRef.current?.addFiles(files)}
Expand DownExpand Up@@ -526,6 +545,7 @@ export const ChatThread = ({
)}
</div>
</ChatPaneDropzone>
</McpToolNameContext.Provider>
</McpServerIconContext.Provider>
</ToolApprovalProvider>
);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -546,6 +546,7 @@ export const StepPartRenderer = ({ part, toolTokenUsageMap }: { part: SBChatMess
case 'data-source':
case 'data-command':
case 'data-mcp-server':
case 'data-mcp-tool':
case 'data-mcp-failed-server':
case 'data-attachment':
case 'file':
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,14 @@

import { Button } from "@/components/ui/button";
import { McpFavicon } from "@/ee/features/chat/mcp/components/mcpFavicon";
import { useMcpServerIconMap} from "@/ee/features/chat/mcpServerIconContext";
import { McpToolNameMap, useMcpServerIconMap, useMcpToolNameMap } from "@/ee/features/chat/mcpDisplayMetadataContext";
import { useToolApproval } from "@/ee/features/chat/toolApprovalContext";
import { SBChatToolPart } from "@/features/chat/utils";
import { cn } from "@/lib/utils";
import { getToolName } from "ai";
import { ChevronRight } from "lucide-react";
import { useCallback, useState } from "react";
import { parseMcpToolName } from "./tools/mcpToolComponent";
import { getMcpToolDisplayParts } from "./tools/mcpToolComponent";
import { JsonHighlighter } from "./tools/jsonHighlighter";

export type ApprovalRequestedToolPart = SBChatToolPart & {
Expand All@@ -23,6 +23,7 @@ interface ToolApprovalBannerProps {
export const ToolApprovalBanner = ({ parts }: ToolApprovalBannerProps) => {
const addToolApprovalResponse = useToolApproval();
const iconMap = useMcpServerIconMap();
const rawToolNames = useMcpToolNameMap();

if (parts.length === 0) {
return null;
Expand All@@ -36,6 +37,7 @@ export const ToolApprovalBanner = ({ parts }: ToolApprovalBannerProps) => {
part={part}
addToolApprovalResponse={addToolApprovalResponse}
iconMap={iconMap}
rawToolNames={rawToolNames}
/>
))}
</div>
Expand All@@ -46,17 +48,17 @@ const ToolApprovalItem = ({
part,
addToolApprovalResponse,
iconMap,
rawToolNames,
}: {
part: ApprovalRequestedToolPart;
addToolApprovalResponse: ReturnType<typeof useToolApproval>;
iconMap: Record<string, string | undefined>;
rawToolNames: McpToolNameMap;
}) => {
const [isExpanded, setIsExpanded] = useState(false);
const partToolName = getToolName(part);
const parsed = parseMcpToolName(partToolName);
const serverName = parsed?.serverName ?? partToolName;
const toolName = parsed?.toolName ?? partToolName;
const faviconUrl = parsed ? iconMap[parsed.serverName] : undefined;
const display = getMcpToolDisplayParts(partToolName, rawToolNames);
const faviconUrl = display.serverName ? iconMap[display.serverName] : undefined;

const requestText = JSON.stringify(part.input, null, 2);

Expand All@@ -83,13 +85,13 @@ const ToolApprovalItem = ({
>
<McpFavicon faviconUrl={faviconUrl} className="w-4 h-4" />
<span className="text-sm text-foreground truncate">
{parsed ? (
{display.serverName ? (
<>
Agent wants to use <span className="font-medium">{toolName}</span> from <span className="font-medium">{serverName}</span>
Agent wants to use <span className="font-medium">{display.toolName}</span> from <span className="font-medium">{display.serverName}</span>
</>
) : (
<>
Agent wants to use <span className="font-medium">{toolName}</span>
Agent wants to use <span className="font-medium">{display.toolName}</span>
</>
)}
</span>
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
import { render, screen } from '@testing-library/react';
import type { DynamicToolUIPart } from 'ai';
import { describe, expect, test } from 'vitest';
import { McpToolNameContext } from '@/ee/features/chat/mcpDisplayMetadataContext';
import { getMcpToolDisplayParts, McpToolComponent } from './mcpToolComponent';

describe('getMcpToolDisplayParts', () => {
test('maps provider-safe MCP tool names back to raw tool names for display', () => {
expect(getMcpToolDisplayParts(
'mcp_backstage__catalog_query-catalog-entities',
{
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
},
)).toEqual({
serverName: 'backstage',
toolName: 'catalog.query-catalog-entities',
displayName: 'backstage: catalog.query-catalog-entities',
});
});

test('falls back to the provider-safe name for older messages without metadata', () => {
expect(getMcpToolDisplayParts('mcp_backstage__catalog_query-catalog-entities')).toEqual({
serverName: 'backstage',
toolName: 'catalog_query-catalog-entities',
displayName: 'backstage: catalog_query-catalog-entities',
});
});
});

describe('McpToolComponent', () => {
test('renders the raw MCP tool name when display metadata is available', () => {
const part = {
type: 'dynamic-tool',
toolName: 'mcp_backstage__catalog_query-catalog-entities',
toolCallId: 'tool-call-1',
state: 'approval-requested',
input: { filter: 'kind=component' },
} as DynamicToolUIPart;

render(
<McpToolNameContext.Provider value={{
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
}}>
<McpToolComponent part={part} />
</McpToolNameContext.Provider>
);

expect(screen.getByText('backstage: catalog.query-catalog-entities')).toBeTruthy();
expect(screen.getByText('Request (backstage: catalog.query-catalog-entities)')).toBeTruthy();
expect(screen.queryByText('backstage: catalog_query-catalog-entities')).toBeNull();
});
});
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,6 +39,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Upgraded `@opentelemetry/core` to `^2.8.0`. [#1413](https://github.com/sourcebot-dev/sourcebot/pull/1413)
- [EE] Fixed connector setup dialogs to add scrolling when connector setup content goes out of view.
- Fixed Gitea sync failing with `ERR_STREAM_PREMATURE_CLOSE` by forcing identity encoding on the Gitea API fetch and guarding against null repository responses. [#1405](https://github.com/sourcebot-dev/sourcebot/pull/1405)
- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Missing PR link in CHANGELOG entry.

Unlike the surrounding entries, this new line has no trailing [#<id>](url) link. As per coding guidelines, "Update CHANGELOG.md with an entry under [Unreleased] linking to the new PR" and "CHANGELOG.md entries must follow the format: single sentence description followed by a link in the format [#<id>](https://github.com/sourcebot-dev/sourcebot/pull/<id>)."

📝 Proposed fix
-- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.+- [EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI. [`#1423`](https://github.com/sourcebot-dev/sourcebot/pull/1423)
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
-[EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.
-[EE] Fixed Ask connector MCP tools with provider-invalid names failing to run by sanitizing model-facing tool names while preserving raw names in the UI.[`#1423`](https://github.com/sourcebot-dev/sourcebot/pull/1423)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@CHANGELOG.md` at line 35, The new CHANGELOG.md entry under [Unreleased] is
missing the required pull request link. Update the entry so the single-sentence
description is followed by the matching
[#<id>](https://github.com/sourcebot-dev/sourcebot/pull/<id>) link, consistent
with the surrounding CHANGELOG entries and the project’s CHANGELOG formatting
rules.

Source: Coding guidelines


## [5.0.4] - 2026-06-18

Expand Down
56 changes: 56 additions & 0 deletions packages/web/src/ee/features/chat/agent.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -265,6 +265,62 @@ beforeEach(() => {
});

describe('createMessageStream approval continuation', () => {
test('streams raw MCP tool names for client display', async () => {
const { getConnectedMcpClients } = await import('@/ee/features/chat/mcp/mcpClientFactory');
const { getMcpTools } = await import('@/ee/features/chat/mcp/mcpToolSets');
vi.mocked(getConnectedMcpClients).mockResolvedValueOnce([
{ serverId: 'server-backstage', serverName: 'Backstage' },
] as never);
vi.mocked(getMcpTools).mockResolvedValueOnce({
tools: {},
failedServers: [],
serverFaviconUrls: {
backstage: 'https://backstage.example.com/favicon.ico',
},
toolDisplayNames: {
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
},
cleanup: vi.fn(),
});
mockAi.streamText.mockReturnValue(createFakeStreamResult());

await createMessageStream({
chatId: 'chat-id',
messages: [createUserMessage()],
selectedRepos: [],
disabledMcpServerIds: [],
prisma: {},
model: {},
modelName: 'test-model',
promptCacheStrategy: noopStrategy,
onFinish: vi.fn(),
onError: () => 'error',
userId: 'user-id',
orgId: 1,
} as unknown as Parameters<typeof createMessageStream>[0]);

const execute = mockAi.latestCreateUIMessageStreamOptions?.execute;
if (!execute) {
throw new Error('Expected createUIMessageStream to capture execute callback.');
}

const write = vi.fn();
await execute({
writer: {
merge: vi.fn(),
write,
},
});

expect(write).toHaveBeenCalledWith({
type: 'data-mcp-tool',
data: {
modelToolName: 'mcp_backstage__catalog_query-catalog-entities',
rawToolName: 'catalog.query-catalog-entities',
},
});
});

test.each([
['dynamic', dynamicApprovalRespondedPart],
['static', staticApprovalRespondedPart],
Expand Down
13 changes: 12 additions & 1 deletion packages/web/src/ee/features/chat/agent.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -369,6 +369,12 @@ export const createMessageStream = async ({
data: { sanitizedName, faviconUrl },
});
},
onMcpToolDiscovered: (modelToolName, rawToolName) => {
writer.write({
type: 'data-mcp-tool',
data: { modelToolName, rawToolName },
});
},
onMcpServerFailed: (serverName) => {
writer.write({
type: 'data-mcp-failed-server',
Expand DownExpand Up@@ -501,6 +507,7 @@ interface AgentOptions {
inputSources: Source[];
onWriteSource: (source: Source) => void;
onMcpServerDiscovered: (sanitizedName: string, faviconUrl: string) => void;
onMcpToolDiscovered: (modelToolName: string, rawToolName: string) => void;
onMcpServerFailed: (serverName: string) => void;
traceId: string;
chatId: string;
Expand All@@ -520,6 +527,7 @@ const createAgentStream = async ({
disabledMcpServerIds,
onWriteSource,
onMcpServerDiscovered,
onMcpToolDiscovered,
onMcpServerFailed,
traceId,
chatId,
Expand DownExpand Up@@ -556,7 +564,7 @@ const createAgentStream = async ({
}))
).filter((source) => source !== undefined);

let mcpToolSetsObj: McpToolsResult = { tools: {}, failedServers: [], serverFaviconUrls: {}, cleanup: async () => {} };
let mcpToolSetsObj: McpToolsResult = { tools: {}, failedServers: [], serverFaviconUrls: {}, toolDisplayNames: {}, cleanup: async () => {} };
if (userId && orgId && await hasEntitlement('ask') && disabledMcpServerIds !== undefined) {
try {
const allMcpClients = await getConnectedMcpClients(prisma, userId, orgId);
Expand All@@ -570,6 +578,9 @@ const createAgentStream = async ({
for (const [sanitizedName, faviconUrl] of Object.entries(mcpToolSetsObj.serverFaviconUrls)) {
onMcpServerDiscovered(sanitizedName, faviconUrl);
}
for (const [modelToolName, rawToolName] of Object.entries(mcpToolSetsObj.toolDisplayNames)) {
onMcpToolDiscovered(modelToolName, rawToolName);
}

if (mcpClients.length > 0) {
logger.info(`Connected to ${mcpClients.length} external MCP server(s): ${mcpClients.map(c => c.serverName).join(', ')}`);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ import { duplicateChat } from '@/features/chat/actions';
import { generateAndUpdateChatNameFromMessage } from '@/ee/features/chat/actions';
import { isServiceError } from '@/lib/utils';
import { NotConfiguredErrorBanner } from '@/features/chat/components/notConfiguredErrorBanner';
import { McpServerIconContext, McpServerIconMap} from '../../mcpServerIconContext';
import { McpServerIconContext, McpServerIconMap, McpToolNameContext, McpToolNameMap } from '../../mcpDisplayMetadataContext';
import { ToolApprovalProvider } from '../../toolApprovalContext';
import useCaptureEvent from '@/hooks/useCaptureEvent';
import { SignInPromptBanner } from './signInPromptBanner';
Expand DownExpand Up@@ -107,6 +107,18 @@ export const ChatThread = ({
return map;
});

const [mcpToolNameMap, setMcpToolNameMap] = useState<McpToolNameMap>(() => {
const map: McpToolNameMap = {};
initialMessages?.forEach((message) => {
message.parts
.filter((part) => part.type === 'data-mcp-tool')
.forEach((part) => {
map[part.data.modelToolName] = part.data.rawToolName;
});
});
return map;
});

const [failedMcpServers, setFailedMcpServers] = useState<string[]>(() => {
const names: string[] = [];
initialMessages?.forEach((message) => {
Expand DownExpand Up@@ -176,6 +188,12 @@ export const ChatThread = ({
[dataPart.data.sanitizedName]: dataPart.data.faviconUrl,
}));
}
if (dataPart.type === 'data-mcp-tool') {
setMcpToolNameMap((prev) => ({
...prev,
[dataPart.data.modelToolName]: dataPart.data.rawToolName,
}));
}
if (dataPart.type === 'data-mcp-failed-server') {
setFailedMcpServers((prev) => {
if (prev.includes(dataPart.data.serverName)) {
Expand DownExpand Up@@ -378,6 +396,7 @@ export const ChatThread = ({
return (
<ToolApprovalProvider value={addToolApprovalResponse}>
<McpServerIconContext.Provider value={mcpServerIconMap}>
<McpToolNameContext.Provider value={mcpToolNameMap}>
<ChatPaneDropzone
className="flex flex-col flex-1 min-h-0 w-full"
onFilesDropped={(files) => chatBoxRef.current?.addFiles(files)}
Expand DownExpand Up@@ -526,6 +545,7 @@ export const ChatThread = ({
)}
</div>
</ChatPaneDropzone>
</McpToolNameContext.Provider>
</McpServerIconContext.Provider>
</ToolApprovalProvider>
);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -546,6 +546,7 @@ export const StepPartRenderer = ({ part, toolTokenUsageMap }: { part: SBChatMess
case 'data-source':
case 'data-command':
case 'data-mcp-server':
case 'data-mcp-tool':
case 'data-mcp-failed-server':
case 'data-attachment':
case 'file':
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,14 @@

import { Button } from "@/components/ui/button";
import { McpFavicon } from "@/ee/features/chat/mcp/components/mcpFavicon";
import { useMcpServerIconMap} from "@/ee/features/chat/mcpServerIconContext";
import { McpToolNameMap, useMcpServerIconMap, useMcpToolNameMap } from "@/ee/features/chat/mcpDisplayMetadataContext";
import { useToolApproval } from "@/ee/features/chat/toolApprovalContext";
import { SBChatToolPart } from "@/features/chat/utils";
import { cn } from "@/lib/utils";
import { getToolName } from "ai";
import { ChevronRight } from "lucide-react";
import { useCallback, useState } from "react";
import { parseMcpToolName } from "./tools/mcpToolComponent";
import { getMcpToolDisplayParts } from "./tools/mcpToolComponent";
import { JsonHighlighter } from "./tools/jsonHighlighter";

export type ApprovalRequestedToolPart = SBChatToolPart & {
Expand All@@ -23,6 +23,7 @@ interface ToolApprovalBannerProps {
export const ToolApprovalBanner = ({ parts }: ToolApprovalBannerProps) => {
const addToolApprovalResponse = useToolApproval();
const iconMap = useMcpServerIconMap();
const rawToolNames = useMcpToolNameMap();

if (parts.length === 0) {
return null;
Expand All@@ -36,6 +37,7 @@ export const ToolApprovalBanner = ({ parts }: ToolApprovalBannerProps) => {
part={part}
addToolApprovalResponse={addToolApprovalResponse}
iconMap={iconMap}
rawToolNames={rawToolNames}
/>
))}
</div>
Expand All@@ -46,17 +48,17 @@ const ToolApprovalItem = ({
part,
addToolApprovalResponse,
iconMap,
rawToolNames,
}: {
part: ApprovalRequestedToolPart;
addToolApprovalResponse: ReturnType<typeof useToolApproval>;
iconMap: Record<string, string | undefined>;
rawToolNames: McpToolNameMap;
}) => {
const [isExpanded, setIsExpanded] = useState(false);
const partToolName = getToolName(part);
const parsed = parseMcpToolName(partToolName);
const serverName = parsed?.serverName ?? partToolName;
const toolName = parsed?.toolName ?? partToolName;
const faviconUrl = parsed ? iconMap[parsed.serverName] : undefined;
const display = getMcpToolDisplayParts(partToolName, rawToolNames);
const faviconUrl = display.serverName ? iconMap[display.serverName] : undefined;

const requestText = JSON.stringify(part.input, null, 2);

Expand All@@ -83,13 +85,13 @@ const ToolApprovalItem = ({
>
<McpFavicon faviconUrl={faviconUrl} className="w-4 h-4" />
<span className="text-sm text-foreground truncate">
{parsed ? (
{display.serverName ? (
<>
Agent wants to use <span className="font-medium">{toolName}</span> from <span className="font-medium">{serverName}</span>
Agent wants to use <span className="font-medium">{display.toolName}</span> from <span className="font-medium">{display.serverName}</span>
</>
) : (
<>
Agent wants to use <span className="font-medium">{toolName}</span>
Agent wants to use <span className="font-medium">{display.toolName}</span>
</>
)}
</span>
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
import { render, screen } from '@testing-library/react';
import type { DynamicToolUIPart } from 'ai';
import { describe, expect, test } from 'vitest';
import { McpToolNameContext } from '@/ee/features/chat/mcpDisplayMetadataContext';
import { getMcpToolDisplayParts, McpToolComponent } from './mcpToolComponent';

describe('getMcpToolDisplayParts', () => {
test('maps provider-safe MCP tool names back to raw tool names for display', () => {
expect(getMcpToolDisplayParts(
'mcp_backstage__catalog_query-catalog-entities',
{
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
},
)).toEqual({
serverName: 'backstage',
toolName: 'catalog.query-catalog-entities',
displayName: 'backstage: catalog.query-catalog-entities',
});
});

test('falls back to the provider-safe name for older messages without metadata', () => {
expect(getMcpToolDisplayParts('mcp_backstage__catalog_query-catalog-entities')).toEqual({
serverName: 'backstage',
toolName: 'catalog_query-catalog-entities',
displayName: 'backstage: catalog_query-catalog-entities',
});
});
});

describe('McpToolComponent', () => {
test('renders the raw MCP tool name when display metadata is available', () => {
const part = {
type: 'dynamic-tool',
toolName: 'mcp_backstage__catalog_query-catalog-entities',
toolCallId: 'tool-call-1',
state: 'approval-requested',
input: { filter: 'kind=component' },
} as DynamicToolUIPart;

render(
<McpToolNameContext.Provider value={{
'mcp_backstage__catalog_query-catalog-entities': 'catalog.query-catalog-entities',
}}>
<McpToolComponent part={part} />
</McpToolNameContext.Provider>
);

expect(screen.getByText('backstage: catalog.query-catalog-entities')).toBeTruthy();
expect(screen.getByText('Request (backstage: catalog.query-catalog-entities)')).toBeTruthy();
expect(screen.queryByText('backstage: catalog_query-catalog-entities')).toBeNull();
});
});
Loading
Loading