fix(server): share MCP tool presentation across providers (#15475)
Co-authored-by: Bil0000 <[email protected]> Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
19 files changed
+958
-107
No files matched your search
@@ -1008,9 +1008,12 @@ describe("AcpAdapterV2", () => {
|
||||
);
|
||||
type Runtime = AcpSessionRuntime.AcpSessionRuntime["Service"];
|
||||
let handler: Parameters<Runtime["handleSessionUpdate"]>[0] | undefined;
|
||||
let createTerminal: Parameters<Runtime["handleCreateTerminal"]>[0] | undefined;
|
||||
const instanceId = ProviderInstanceId.make("devin-replay");
|
||||
const adapter = makeAcpAdapterV2({
|
||||
instanceId,
|
||||
// Production Devin runs commands through client terminals.
|
||||
clientTerminals: { childProcessSpawner, shellCommands: true },
|
||||
crypto: yield* Crypto.Crypto,
|
||||
fileSystem: yield* FileSystem.FileSystem,
|
||||
idAllocator,
|
||||
@@ -1031,9 +1034,18 @@ describe("AcpAdapterV2", () => {
|
||||
Effect.sync(() => {
|
||||
handler = next;
|
||||
}).pipe(Effect.andThen(runtime.handleSessionUpdate(next))),
|
||||
handleCreateTerminal: (next) =>
|
||||
Effect.sync(() => {
|
||||
createTerminal = next;
|
||||
}).pipe(Effect.andThen(runtime.handleCreateTerminal(next))),
|
||||
prompt: () =>
|
||||
Effect.gen(function* () {
|
||||
assert.isDefined(handler);
|
||||
assert.isDefined(createTerminal);
|
||||
const fallbackTerminal = yield* createTerminal(
|
||||
{ sessionId: "mock-session-1", command: "true acp-mcp-call task_status {}" },
|
||||
{ requestId: "child-mcp-terminal", method: "terminal/create" },
|
||||
);
|
||||
// Production thread 54aeb6d7 split after "(command". Metadata shapes
|
||||
// below were captured from live Devin sessions showy-mile/fragrant-chamomile.
|
||||
const updates = [
|
||||
@@ -1075,6 +1087,48 @@ describe("AcpAdapterV2", () => {
|
||||
"cognition.ai/subagent_context": { parentAgentId: "child-a" },
|
||||
},
|
||||
},
|
||||
{
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "child-weather",
|
||||
title: "Check weather",
|
||||
status: "completed",
|
||||
rawInput: { server: "weather", tool: "get_weather", city: "Berlin" },
|
||||
rawOutput: {
|
||||
result: {
|
||||
_meta: {
|
||||
source: { name: "Weather", logoUrl: "https://example.com/weather.png" },
|
||||
},
|
||||
content: [{ type: "text", text: "Sunny" }],
|
||||
},
|
||||
},
|
||||
_meta: {
|
||||
is_mcp_tool_call: true,
|
||||
"cognition.ai/subagent_context": { parentAgentId: "child-a" },
|
||||
},
|
||||
},
|
||||
{
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "child-mcp-fallback",
|
||||
title: "Ran command",
|
||||
kind: "execute",
|
||||
status: "completed",
|
||||
content: [{ type: "terminal", terminalId: fallbackTerminal.terminalId }],
|
||||
_meta: { "cognition.ai/subagent_context": { parentAgentId: "child-a" } },
|
||||
},
|
||||
{
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "parent-weather",
|
||||
title: "Check weather",
|
||||
status: "completed",
|
||||
rawInput: { server: "weather", tool: "get_weather", city: "Berlin" },
|
||||
rawOutput: {
|
||||
_meta: {
|
||||
source: { name: "Weather", logoUrl: "https://example.com/weather.png" },
|
||||
},
|
||||
content: [{ type: "text", text: "Sunny" }],
|
||||
},
|
||||
_meta: { is_mcp_tool_call: true },
|
||||
},
|
||||
{
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: " → decider → event)." },
|
||||
@@ -1192,6 +1246,37 @@ describe("AcpAdapterV2", () => {
|
||||
);
|
||||
assert.deepEqual([...childMessages.values()], ["Checking the code.", "ONE"]);
|
||||
assert.equal(task?.prompt, "Run pwd, then reply ONE.");
|
||||
// Terminal-fallback MCP calls in a child session keep their T3 identity.
|
||||
assert.isTrue(
|
||||
items.some(
|
||||
(item) =>
|
||||
item.threadId === task?.childThreadId &&
|
||||
item.type === "dynamic_tool" &&
|
||||
item.toolName === "t3-code.task_status",
|
||||
),
|
||||
);
|
||||
const childMcp = items.find(
|
||||
(item) =>
|
||||
item.threadId === task?.childThreadId &&
|
||||
item.type === "dynamic_tool" &&
|
||||
item.toolName === "weather.get_weather",
|
||||
);
|
||||
const parentMcp = items.find(
|
||||
(item) =>
|
||||
item.threadId === threadId &&
|
||||
item.type === "dynamic_tool" &&
|
||||
item.toolName === "weather.get_weather",
|
||||
);
|
||||
for (const item of [parentMcp, childMcp]) {
|
||||
assert.equal(item?.title, "get weather");
|
||||
assert.deepEqual(item?.toolSource, {
|
||||
key: "mcp:weather",
|
||||
name: "Weather",
|
||||
kind: "integration",
|
||||
icon: { _tag: "themed-logo", logoUrl: "https://example.com/weather.png" },
|
||||
});
|
||||
assert.deepEqual(item?.toolIcon, item?.toolSource?.icon);
|
||||
}
|
||||
assert.isTrue(
|
||||
items.some(
|
||||
(item) =>
|
||||
@@ -1216,7 +1301,7 @@ describe("AcpAdapterV2", () => {
|
||||
const parentTools = items.filter(
|
||||
(item) => item.threadId === threadId && item.type === "dynamic_tool",
|
||||
);
|
||||
assert.equal(parentTools.length, 1);
|
||||
assert.equal(parentTools.length, 2);
|
||||
assert.equal(parentTools[0]?.title, "Parent tool finished");
|
||||
}).pipe(Effect.provide(testLayer), Effect.scoped),
|
||||
);
|
||||
|
||||
@@ -63,6 +63,7 @@ import {
|
||||
makeAcpMcpOverAcpBridge,
|
||||
type AcpMcpOverAcpBridge,
|
||||
} from "../../mcp/AcpMcpOverAcpBridge.ts";
|
||||
import { mcpToolPresentation } from "../../provider/McpToolPresentation.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import {
|
||||
applyAcpAgentTerminalUpdate,
|
||||
@@ -1632,6 +1633,21 @@ export function makeAcpAdapterV2(
|
||||
embeddedTerminalsByToolCallId.delete(oldest);
|
||||
}
|
||||
};
|
||||
// Command lines of the terminals embedded in a tool call, so MCP calls
|
||||
// made through the acp-mcp-call terminal fallback keep their identity.
|
||||
const embeddedTerminalCommands = (
|
||||
sessionId: string,
|
||||
toolCallId: string,
|
||||
): ReadonlyArray<string> =>
|
||||
(
|
||||
embeddedTerminalsByToolCallId.get(sessionScopedId(sessionId, toolCallId))
|
||||
?.terminalIds ?? []
|
||||
).flatMap((terminalId) => {
|
||||
const command =
|
||||
clientTerminals?.readCommandLine(terminalId) ??
|
||||
agentTerminalsById.get(sessionScopedId(sessionId, terminalId))?.command;
|
||||
return command === undefined ? [] : [command];
|
||||
});
|
||||
// Client terminals (Devin) run with the T3 server's privileges, so they
|
||||
// are policy-checked against the active turn policy; a command the user
|
||||
// already approved satisfies an "ask" disposition.
|
||||
@@ -3267,17 +3283,10 @@ export function makeAcpAdapterV2(
|
||||
// agent-specific shape and project the same branded dynamic_tool
|
||||
// item native providers produce (e.g. the T3 orchestration tools).
|
||||
const mcpIdentity = extractMcpToolCallIdentity(toolCall, {
|
||||
embeddedTerminalCommands: (
|
||||
embeddedTerminalsByToolCallId.get(
|
||||
sessionScopedId(context.nativeThreadId, toolCall.toolCallId),
|
||||
)?.terminalIds ?? []
|
||||
).flatMap((terminalId) => {
|
||||
const command =
|
||||
clientTerminals?.readCommandLine(terminalId) ??
|
||||
agentTerminalsById.get(sessionScopedId(context.nativeThreadId, terminalId))
|
||||
?.command;
|
||||
return command === undefined ? [] : [command];
|
||||
}),
|
||||
embeddedTerminalCommands: embeddedTerminalCommands(
|
||||
context.nativeThreadId,
|
||||
toolCall.toolCallId,
|
||||
),
|
||||
});
|
||||
let turnItem: OrchestrationV2TurnItem;
|
||||
if (toolCall.toolCallId.startsWith("acp-compaction:")) {
|
||||
@@ -3302,9 +3311,14 @@ export function makeAcpAdapterV2(
|
||||
} else if (mcpIdentity !== undefined) {
|
||||
turnItem = {
|
||||
...base,
|
||||
// Identity lives in toolName, like native Codex MCP items; the
|
||||
// agent's own title (e.g. "Ran command") would shadow it.
|
||||
title: null,
|
||||
...mcpToolPresentation({
|
||||
serverName: mcpIdentity.server,
|
||||
toolName: mcpIdentity.tool,
|
||||
source: unknownRecord(
|
||||
(unknownRecord(rawOutputRecord?.result) ?? rawOutputRecord)?._meta,
|
||||
)?.source,
|
||||
}),
|
||||
type: "dynamic_tool",
|
||||
toolName: `${mcpIdentity.server}.${mcpIdentity.tool}`,
|
||||
input:
|
||||
@@ -4328,7 +4342,8 @@ export function makeAcpAdapterV2(
|
||||
return;
|
||||
}
|
||||
if (context.finalized) return;
|
||||
if (notification.sessionId !== (yield* Ref.get(activeSessionId))) {
|
||||
const rootSessionId = yield* Ref.get(activeSessionId);
|
||||
if (notification.sessionId !== rootSessionId) {
|
||||
// Finalize may have completed during the activeSessionId yield.
|
||||
if (context.finalized) return;
|
||||
if (flavor.extractSubagentUpdate === undefined) return;
|
||||
@@ -4356,6 +4371,17 @@ export function makeAcpAdapterV2(
|
||||
const key = `${nativeTaskId}:tool:${toolCall.toolCallId}`;
|
||||
const merged = mergeToolCallState(context.tools.get(key), toolCall);
|
||||
context.tools.set(key, merged);
|
||||
// Terminals are remembered under the raw session id: the child's
|
||||
// own session, or the root one when the flavor routes child
|
||||
// updates out of it (Devin).
|
||||
const mcpIdentity = extractMcpToolCallIdentity(merged, {
|
||||
embeddedTerminalCommands: [
|
||||
...embeddedTerminalCommands(notification.sessionId, toolCall.toolCallId),
|
||||
...(rootSessionId === null
|
||||
? []
|
||||
: embeddedTerminalCommands(rootSessionId, toolCall.toolCallId)),
|
||||
],
|
||||
});
|
||||
const now = yield* DateTime.now;
|
||||
const status = toolStatus(merged.status);
|
||||
const startedAt = context.toolStartedAt.get(key) ?? now;
|
||||
@@ -4380,7 +4406,22 @@ export function makeAcpAdapterV2(
|
||||
completedAt: completedAtForStatus(status, now),
|
||||
updatedAt: now,
|
||||
type: "dynamic_tool",
|
||||
toolName: merged.title ?? merged.kind ?? "Tool",
|
||||
...(mcpIdentity === undefined
|
||||
? {}
|
||||
: mcpToolPresentation({
|
||||
serverName: mcpIdentity.server,
|
||||
toolName: mcpIdentity.tool,
|
||||
source: unknownRecord(
|
||||
(
|
||||
unknownRecord(unknownRecord(merged.data.rawOutput)?.result) ??
|
||||
unknownRecord(merged.data.rawOutput)
|
||||
)?._meta,
|
||||
)?.source,
|
||||
})),
|
||||
toolName:
|
||||
mcpIdentity === undefined
|
||||
? (merged.title ?? merged.kind ?? "Tool")
|
||||
: `${mcpIdentity.server}.${mcpIdentity.tool}`,
|
||||
input: merged.data.rawInput ?? null,
|
||||
output: merged.data.rawOutput ?? merged.data.content ?? null,
|
||||
},
|
||||
|
||||
@@ -2195,6 +2195,111 @@ describe("ClaudeAdapterV2 background wake turns", () => {
|
||||
});
|
||||
const makeWakeHarness = makeWakeHarnessWithOptions();
|
||||
|
||||
it.effect.each([
|
||||
{ isError: false, title: "Check weather" },
|
||||
{ isError: true, title: "Check weather" },
|
||||
{ isError: false, title: undefined },
|
||||
])("keeps late MCP display metadata with %j", ({ isError, title }) =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeWakeHarness;
|
||||
yield* harness.runtime.startTurn(
|
||||
makeClaudeTestTurnInput({
|
||||
threadId: harness.threadId,
|
||||
providerThread: harness.providerThread,
|
||||
now: yield* DateTime.now,
|
||||
attemptId: RunAttemptId.make("mcp-presentation"),
|
||||
text: "Check the weather",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
const toolName = "mcp__weather__get_weather";
|
||||
const id = "weather-call";
|
||||
yield* Effect.promise(() =>
|
||||
harness.getOpenedOptions()!.canUseTool!(
|
||||
toolName,
|
||||
{ city: "Berlin" },
|
||||
{
|
||||
signal: new AbortController().signal,
|
||||
toolUseID: id,
|
||||
requestId: "weather-request",
|
||||
},
|
||||
),
|
||||
);
|
||||
yield* harness.offerAndWait(
|
||||
claudeSdkFrame({
|
||||
type: "assistant",
|
||||
uuid: "weather-assistant",
|
||||
session_id: WAKE_NATIVE_SESSION,
|
||||
parent_tool_use_id: null,
|
||||
message: {
|
||||
id: "weather-message",
|
||||
type: "message",
|
||||
role: "assistant",
|
||||
model: "claude-sonnet-4-6",
|
||||
content: [{ type: "tool_use", id, name: toolName, input: { city: "Berlin" } }],
|
||||
},
|
||||
tool_use_meta: [
|
||||
{
|
||||
id,
|
||||
display_name: title,
|
||||
server_display_name: "Weather",
|
||||
icon_url: "https://example.com/weather.png",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
yield* harness.offerAndWait(
|
||||
claudeSdkFrame({
|
||||
type: "user",
|
||||
uuid: "weather-result",
|
||||
session_id: WAKE_NATIVE_SESSION,
|
||||
parent_tool_use_id: null,
|
||||
message: {
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "tool_result",
|
||||
tool_use_id: id,
|
||||
content: "Weather result",
|
||||
is_error: isError,
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
yield* Queue.offer(
|
||||
harness.sdkMessages,
|
||||
makeResultFrame({ uuid: "weather-terminal", result: "Weather checked" }),
|
||||
);
|
||||
yield* Queue.take(harness.terminalReceipts);
|
||||
const items = harness.events.flatMap((event) =>
|
||||
event.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool"
|
||||
? [event.turnItem]
|
||||
: [],
|
||||
);
|
||||
assert.deepEqual(
|
||||
items.map((item) => item.status),
|
||||
["running", "running", isError ? "failed" : "completed"],
|
||||
);
|
||||
assert.isNull(items[0]?.title);
|
||||
for (const item of items.slice(1)) {
|
||||
assert.equal(item.title, title ?? "get weather");
|
||||
assert.deepEqual(item.toolIcon, {
|
||||
_tag: "themed-logo",
|
||||
logoUrl: "https://example.com/weather.png",
|
||||
});
|
||||
assert.deepEqual(item.toolSource, {
|
||||
key: "mcp:weather",
|
||||
name: "Weather",
|
||||
kind: "integration",
|
||||
icon: { _tag: "themed-logo", logoUrl: "https://example.com/weather.png" },
|
||||
});
|
||||
assert.deepEqual(item.input, { city: "Berlin" });
|
||||
}
|
||||
assert.equal(new Set(items.map((item) => item.id)).size, 1);
|
||||
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"reuses a background shell's query for omitted and explicit Normal, but blocks Fast",
|
||||
() =>
|
||||
|
||||
@@ -67,7 +67,6 @@ import {
|
||||
type ProviderUserInputAnswers,
|
||||
type ProviderThreadId,
|
||||
type ThreadId,
|
||||
type ToolActivitySource,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as Cause from "effect/Cause";
|
||||
@@ -116,6 +115,7 @@ import type { ServerProviderShape } from "../../provider/Services/ServerProvider
|
||||
import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts";
|
||||
import { T3_CODE_ORCHESTRATION_INSTRUCTIONS } from "../../provider/T3OrchestrationInstructions.ts";
|
||||
import { buildRuntimeInstructions } from "../../provider/RuntimeInstructions.ts";
|
||||
import { mcpToolPresentation, normalizeMcpText } from "../../provider/McpToolPresentation.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import * as IdAllocator from "../IdAllocator.ts";
|
||||
import { makeProviderFailure, makeProviderRetryTurnItem } from "../ProviderFailure.ts";
|
||||
@@ -2089,62 +2089,33 @@ function claudeToolUseBlocksFromAssistantMessage(
|
||||
return message.message.content.filter(isClaudeToolUseContentBlock);
|
||||
}
|
||||
|
||||
interface ClaudeToolPresentation {
|
||||
readonly title: string;
|
||||
readonly toolSource?: ToolActivitySource;
|
||||
}
|
||||
type ClaudeToolPresentation = ReturnType<typeof mcpToolPresentation>;
|
||||
|
||||
function boundedMetaText(value: unknown, maxLength: number): string | undefined {
|
||||
if (typeof value !== "string") return undefined;
|
||||
const text = value.trim().replace(/\s+/gu, " ");
|
||||
return text.length > 0 && text.length <= maxLength ? text : undefined;
|
||||
}
|
||||
|
||||
function metaHttpUrl(value: unknown): string | undefined {
|
||||
if (typeof value !== "string" || value.length > 4096) return undefined;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return (url.protocol === "https:" || url.protocol === "http:") && url.href.length <= 4096
|
||||
? url.href
|
||||
: undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Claude Code's own label for each tool use (the MCP tool's title, or its
|
||||
* humanized name) plus the server's name and icon. The CLI sends these as
|
||||
* `tool_use_meta` on assistant frames; the SDK types do not declare it yet.
|
||||
*/
|
||||
function claudeToolPresentationsFromAssistantMessage(
|
||||
message: SDKMessage,
|
||||
): ReadonlyMap<string, ClaudeToolPresentation> {
|
||||
const presentations = new Map<string, ClaudeToolPresentation>();
|
||||
const meta = message.type === "assistant" ? Reflect.get(message, "tool_use_meta") : undefined;
|
||||
if (!Array.isArray(meta)) return presentations;
|
||||
const toolNames = new Map(
|
||||
claudeToolUseBlocksFromAssistantMessage(message).map((tool) => [
|
||||
tool.id,
|
||||
tool.name.replace(/^mcp__claude_ai_/u, "mcp__"),
|
||||
]),
|
||||
);
|
||||
for (const entry of meta) {
|
||||
if (typeof entry !== "object" || entry === null) continue;
|
||||
const id = boundedMetaText(Reflect.get(entry, "id"), 512);
|
||||
const title = boundedMetaText(Reflect.get(entry, "display_name"), 160);
|
||||
if (id === undefined || title === undefined) continue;
|
||||
const serverName = boundedMetaText(Reflect.get(entry, "server_display_name"), 160);
|
||||
const iconUrl = metaHttpUrl(Reflect.get(entry, "icon_url"));
|
||||
presentations.set(id, {
|
||||
title,
|
||||
...(serverName === undefined
|
||||
? {}
|
||||
: {
|
||||
toolSource: {
|
||||
key: `mcp:${serverName.toLowerCase()}`,
|
||||
name: serverName,
|
||||
kind: "integration",
|
||||
...(iconUrl === undefined
|
||||
? {}
|
||||
: { icon: { _tag: "themed-logo", logoUrl: iconUrl } as const }),
|
||||
},
|
||||
}),
|
||||
});
|
||||
const id = normalizeMcpText(Reflect.get(entry, "id"), 512);
|
||||
if (id === undefined) continue;
|
||||
presentations.set(
|
||||
id,
|
||||
mcpToolPresentation({
|
||||
toolName: toolNames.get(id),
|
||||
title: Reflect.get(entry, "display_name"),
|
||||
serverDisplayName: Reflect.get(entry, "server_display_name"),
|
||||
iconUrl: Reflect.get(entry, "icon_url"),
|
||||
}),
|
||||
);
|
||||
}
|
||||
return presentations;
|
||||
}
|
||||
@@ -3878,6 +3849,9 @@ export function makeClaudeAdapterV2(
|
||||
: {
|
||||
...itemBase,
|
||||
type: "dynamic_tool",
|
||||
...(input.presentation?.toolIcon === undefined
|
||||
? {}
|
||||
: { toolIcon: input.presentation.toolIcon }),
|
||||
...(input.presentation?.toolSource === undefined
|
||||
? {}
|
||||
: { toolSource: input.presentation.toolSource }),
|
||||
@@ -6053,7 +6027,11 @@ export function makeClaudeAdapterV2(
|
||||
toolName: toolUse.name,
|
||||
toolInput: nativeToolInput,
|
||||
parentToolUseId: parentToolUseIdFromSdkMessage(message),
|
||||
presentation: toolPresentations.get(toolUse.id),
|
||||
presentation:
|
||||
toolPresentations.get(toolUse.id) ??
|
||||
mcpToolPresentation({
|
||||
toolName: toolUse.name.replace(/^mcp__claude_ai_/u, "mcp__"),
|
||||
}),
|
||||
});
|
||||
const heldPlan = heldProposedPlansByToolUseId.get(toolUse.id);
|
||||
if (heldPlan !== undefined) {
|
||||
|
||||
@@ -823,14 +823,62 @@ describe("CodexAdapterV2 dynamic tool projection", () => {
|
||||
);
|
||||
assert.equal(
|
||||
CodexAdapterV2.projectCodexDynamicToolItem({ ...call, arguments: { title: " " } }).title,
|
||||
undefined,
|
||||
"js",
|
||||
);
|
||||
assert.equal(
|
||||
CodexAdapterV2.projectCodexDynamicToolItem({ ...call, server: "github" }).title,
|
||||
undefined,
|
||||
"js",
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["inProgress", "completed", "failed"] as const)(
|
||||
"presents ordinary MCP calls when %s",
|
||||
(status) => {
|
||||
const projection = CodexAdapterV2.projectCodexDynamicToolItem({
|
||||
type: "mcpToolCall",
|
||||
id: "weather-call",
|
||||
server: "weather",
|
||||
tool: "get_weather",
|
||||
status,
|
||||
arguments: { city: "Berlin" },
|
||||
});
|
||||
assert.equal(projection.title, "get weather");
|
||||
assert.deepEqual(projection.toolSource, {
|
||||
key: "mcp:weather",
|
||||
name: "weather",
|
||||
kind: "integration",
|
||||
});
|
||||
assert.deepEqual(projection.input, { city: "Berlin" });
|
||||
},
|
||||
);
|
||||
|
||||
it("uses Codex connector names without reading a display title from arguments", () => {
|
||||
const projection = CodexAdapterV2.projectCodexDynamicToolItem({
|
||||
type: "mcpToolCall",
|
||||
id: "connector-call",
|
||||
server: "_apps",
|
||||
tool: "connector_get_weather",
|
||||
status: "completed",
|
||||
arguments: { title: "Argument, not display metadata" },
|
||||
appContext: {
|
||||
connectorId: "weather-app",
|
||||
appName: "Weather",
|
||||
actionName: "Check weather",
|
||||
},
|
||||
result: {
|
||||
content: [],
|
||||
_meta: { source: { logoUrl: "https://example.com/weather.png" } },
|
||||
},
|
||||
});
|
||||
assert.equal(projection.title, "Check weather");
|
||||
assert.equal(projection.toolSource?.name, "Weather");
|
||||
assert.deepEqual(projection.toolIcon, {
|
||||
_tag: "themed-logo",
|
||||
logoUrl: "https://example.com/weather.png",
|
||||
});
|
||||
assert.deepEqual(projection.toolSource?.icon, projection.toolIcon);
|
||||
});
|
||||
|
||||
it("preserves native browser and app icons alongside MCP tool output", () => {
|
||||
const browser = CodexAdapterV2.projectCodexDynamicToolItem({
|
||||
type: "mcpToolCall",
|
||||
|
||||
@@ -489,9 +489,10 @@ export function projectCodexDynamicToolItem(
|
||||
item.type === "mcpToolCall"
|
||||
? `${item.server}.${item.tool}`
|
||||
: [trimText(item.namespace), item.tool].filter(Boolean).join(".");
|
||||
const title = dynamicToolTitle(toolName, item.arguments);
|
||||
const presentation = item.type === "mcpToolCall" ? mcpToolPresentation(item) : {};
|
||||
const title = dynamicToolTitle(toolName, item.arguments) ?? presentation.title;
|
||||
const projection: CodexDynamicToolProjection = {
|
||||
...(item.type === "mcpToolCall" ? mcpToolPresentation(item) : {}),
|
||||
...presentation,
|
||||
toolName,
|
||||
...(title ? { title } : {}),
|
||||
input: item.arguments,
|
||||
|
||||
@@ -359,6 +359,22 @@ describe("CursorAdapterV2", () => {
|
||||
numFiles: 0,
|
||||
};
|
||||
const updates: ReadonlyArray<InteractionUpdate> = [
|
||||
...(["tool-call-started", "tool-call-completed"] as const).map((type) => ({
|
||||
type,
|
||||
modelCallId: "native-model-call",
|
||||
callId: "mcp-weather",
|
||||
toolCall: {
|
||||
type: "mcp" as const,
|
||||
args: {
|
||||
providerIdentifier: "weather",
|
||||
toolName: "get_weather",
|
||||
args: { city: "Berlin" },
|
||||
},
|
||||
...(type === "tool-call-completed"
|
||||
? { result: { status: "success" as const, value: { content: [], isError: false } } }
|
||||
: {}),
|
||||
},
|
||||
})),
|
||||
{
|
||||
type: "tool-call-completed",
|
||||
modelCallId: "native-model-call",
|
||||
@@ -625,6 +641,30 @@ describe("CursorAdapterV2", () => {
|
||||
Stream.takeUntil((event) => event.type === "turn.terminal"),
|
||||
Stream.runCollect,
|
||||
);
|
||||
const mcpItems = events.flatMap((event) =>
|
||||
event.type === "turn_item.updated" &&
|
||||
event.turnItem.type === "dynamic_tool" &&
|
||||
event.turnItem.toolName === "mcp__weather__get_weather"
|
||||
? [event.turnItem]
|
||||
: [],
|
||||
);
|
||||
assert.deepEqual(
|
||||
mcpItems.map((item) => item.status),
|
||||
["running", "completed"],
|
||||
);
|
||||
for (const item of mcpItems) {
|
||||
assert.equal(item.title, "get weather");
|
||||
assert.deepEqual(item.toolSource, {
|
||||
key: "mcp:weather",
|
||||
name: "weather",
|
||||
kind: "integration",
|
||||
});
|
||||
assert.deepEqual(item.input, {
|
||||
providerIdentifier: "weather",
|
||||
toolName: "get_weather",
|
||||
args: { city: "Berlin" },
|
||||
});
|
||||
}
|
||||
const fileSearchItems = events.flatMap((event) =>
|
||||
event.type === "turn_item.updated" &&
|
||||
event.turnItem.type === "file_search" &&
|
||||
|
||||
@@ -44,6 +44,7 @@ import * as Stream from "effect/Stream";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import { mcpToolPresentation } from "../../provider/McpToolPresentation.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import { CursorTransportFailure } from "../../provider/acp/CursorTransportFailure.ts";
|
||||
import { cursorSdkModelSelection } from "../../provider/cursorSdkModel.ts";
|
||||
@@ -1282,6 +1283,12 @@ export function makeCursorAdapterV2(
|
||||
turnItem = {
|
||||
...base,
|
||||
type: "dynamic_tool",
|
||||
...(toolCall.type === "mcp"
|
||||
? mcpToolPresentation({
|
||||
serverName: toolCall.args.providerIdentifier,
|
||||
toolName: toolCall.args.toolName,
|
||||
})
|
||||
: {}),
|
||||
toolName: cursorToolName(toolCall),
|
||||
input: toolCall.args,
|
||||
...(cursorToolOutput(toolCall) === undefined
|
||||
|
||||
@@ -902,6 +902,250 @@ describe("OpenCodeAdapterV2", () => {
|
||||
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("presents OpenCode MCP calls without treating remote tools as local edits", () =>
|
||||
Effect.gen(function* () {
|
||||
const nativeEvents = asyncEventStream();
|
||||
const nativeSessionId = "native-opencode-mcp";
|
||||
let statusReads = 0;
|
||||
const harness = yield* makeOpenCodeRuntimeHarness("mcp-presentation", nativeSessionId, {
|
||||
event: {
|
||||
subscribe: async (_input: unknown, options: { signal?: AbortSignal }) => {
|
||||
options.signal?.addEventListener("abort", () => nativeEvents.close(), { once: true });
|
||||
return { stream: nativeEvents.stream };
|
||||
},
|
||||
},
|
||||
session: {
|
||||
create: async () => ({ data: { id: nativeSessionId, time: { created: 1, updated: 1 } } }),
|
||||
promptAsync: async () => ({ data: true }),
|
||||
},
|
||||
mcp: {
|
||||
status: async () => {
|
||||
statusReads++;
|
||||
return {
|
||||
data: {
|
||||
"my.server_with_underscores": { status: "connected" },
|
||||
ambiguous: { status: "connected" },
|
||||
ambiguous_server: { status: "connected" },
|
||||
code: { status: "connected" },
|
||||
apply: { status: "connected" },
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
});
|
||||
yield* harness.startTurn();
|
||||
const received = yield* harness.runtime.events.pipe(
|
||||
Stream.takeUntil(
|
||||
(event) => event.type === "turn_item.updated" && event.turnItem.type === "compaction",
|
||||
),
|
||||
Stream.runCollect,
|
||||
Effect.forkScoped,
|
||||
);
|
||||
for (const status of ["running", "completed", "error"] as const) {
|
||||
yield* Effect.promise(() =>
|
||||
nativeEvents.push({
|
||||
type: "message.part.updated",
|
||||
properties: {
|
||||
sessionID: nativeSessionId,
|
||||
part: {
|
||||
id: "mcp-part",
|
||||
sessionID: nativeSessionId,
|
||||
messageID: "mcp-assistant",
|
||||
type: "tool",
|
||||
callID: "mcp-call",
|
||||
tool: "my_server_with_underscores_edit_document",
|
||||
state: {
|
||||
status,
|
||||
input: { document: "remote-doc" },
|
||||
title: "Edit remote document",
|
||||
metadata: {},
|
||||
output: "saved",
|
||||
error: "failed",
|
||||
time: { start: 1, end: 2 },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
yield* Effect.promise(() =>
|
||||
nativeEvents.push({
|
||||
type: "message.part.updated",
|
||||
properties: {
|
||||
sessionID: nativeSessionId,
|
||||
part: {
|
||||
id: "ambiguous-part",
|
||||
sessionID: nativeSessionId,
|
||||
messageID: "mcp-assistant",
|
||||
type: "tool",
|
||||
callID: "ambiguous-call",
|
||||
tool: "ambiguous_server_edit_document",
|
||||
state: {
|
||||
status: "completed",
|
||||
input: {},
|
||||
title: "Ambiguous tool",
|
||||
metadata: {},
|
||||
output: "",
|
||||
time: { start: 1, end: 2 },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
for (const tool of ["code_search", "apply_patch"]) {
|
||||
yield* Effect.promise(() =>
|
||||
nativeEvents.push({
|
||||
type: "message.part.updated",
|
||||
properties: {
|
||||
sessionID: nativeSessionId,
|
||||
part: {
|
||||
id: `native-${tool}`,
|
||||
sessionID: nativeSessionId,
|
||||
messageID: "mcp-assistant",
|
||||
type: "tool",
|
||||
callID: `native-${tool}`,
|
||||
tool,
|
||||
state: {
|
||||
status: "completed",
|
||||
input: { query: "needle", filePath: "local.ts" },
|
||||
title: `Native ${tool}`,
|
||||
metadata: {},
|
||||
output: "done",
|
||||
time: { start: 1, end: 2 },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
yield* Effect.promise(() =>
|
||||
nativeEvents.push({
|
||||
type: "session.compacted",
|
||||
properties: { sessionID: nativeSessionId },
|
||||
}),
|
||||
);
|
||||
const allItems = (yield* Fiber.join(received)).flatMap((event) =>
|
||||
event.type === "turn_item.updated" ? [event.turnItem] : [],
|
||||
);
|
||||
assert.equal(
|
||||
allItems.find((item) => item.title === "Native code_search")?.type,
|
||||
"web_search",
|
||||
);
|
||||
assert.equal(
|
||||
allItems.find((item) => item.title === "Native apply_patch")?.type,
|
||||
"file_change",
|
||||
);
|
||||
const items = allItems.filter((item) => item.type === "dynamic_tool");
|
||||
assert.deepEqual(
|
||||
items.slice(0, 3).map((item) => item.status),
|
||||
["running", "completed", "failed"],
|
||||
);
|
||||
assert.deepEqual(
|
||||
items.slice(0, 3).map((item) => item.title),
|
||||
["Edit remote document", "Edit remote document", "edit document"],
|
||||
);
|
||||
for (const item of items.slice(0, 3)) {
|
||||
assert.deepEqual(item.toolSource, {
|
||||
key: "mcp:my.server_with_underscores",
|
||||
name: "my.server with underscores",
|
||||
kind: "integration",
|
||||
});
|
||||
assert.deepEqual(item.input, { document: "remote-doc" });
|
||||
}
|
||||
assert.equal(items[3]?.toolName, "ambiguous_server_edit_document");
|
||||
assert.isUndefined(items[3]?.toolSource);
|
||||
assert.equal(statusReads, 1);
|
||||
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect.each(["failure", "timeout"] as const)("retries MCP status after %s", (failure) =>
|
||||
Effect.gen(function* () {
|
||||
const nativeEvents = asyncEventStream();
|
||||
const called = promiseGate<void>();
|
||||
const sessionId = `mcp-status-${failure}`;
|
||||
let statusReads = 0;
|
||||
let signal: AbortSignal | undefined;
|
||||
const harness = yield* makeOpenCodeRuntimeHarness(sessionId, sessionId, {
|
||||
event: { subscribe: async () => ({ stream: nativeEvents.stream }) },
|
||||
session: {
|
||||
create: async () => ({ data: { id: sessionId, time: { created: 1, updated: 1 } } }),
|
||||
promptAsync: async () => ({ data: true }),
|
||||
},
|
||||
mcp: {
|
||||
status: async (_input: unknown, options: { signal?: AbortSignal }) => {
|
||||
statusReads++;
|
||||
if (statusReads === 1) {
|
||||
signal = options?.signal;
|
||||
called.resolve();
|
||||
if (failure === "timeout") return new Promise(() => {});
|
||||
throw new Error("MCP status unavailable");
|
||||
}
|
||||
return { data: { weather: { status: "connected" } } };
|
||||
},
|
||||
},
|
||||
});
|
||||
yield* harness.startTurn();
|
||||
const received = yield* harness.runtime.events.pipe(
|
||||
Stream.takeUntil(
|
||||
(event) => event.type === "turn_item.updated" && event.turnItem.type === "compaction",
|
||||
),
|
||||
Stream.runCollect,
|
||||
Effect.forkScoped,
|
||||
);
|
||||
for (const status of ["running", "completed"] as const) {
|
||||
const emitted = yield* Effect.promise(() =>
|
||||
nativeEvents.push({
|
||||
type: "message.part.updated",
|
||||
properties: {
|
||||
sessionID: sessionId,
|
||||
part: {
|
||||
id: "weather-part",
|
||||
sessionID: sessionId,
|
||||
messageID: "weather-message",
|
||||
type: "tool",
|
||||
callID: "weather-call",
|
||||
tool: "weather_edit_document",
|
||||
state: {
|
||||
status,
|
||||
input: { document: "remote-doc" },
|
||||
title: "Edit remote document",
|
||||
metadata: {},
|
||||
output: "saved",
|
||||
time: { start: 1, end: 2 },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
if (status === "running" && failure === "timeout") {
|
||||
yield* Effect.promise(() => called.promise);
|
||||
yield* TestClock.adjust("1 second");
|
||||
}
|
||||
yield* Fiber.join(emitted);
|
||||
}
|
||||
yield* Effect.promise(() =>
|
||||
nativeEvents.push({ type: "session.compacted", properties: { sessionID: sessionId } }),
|
||||
);
|
||||
const completed = (yield* Fiber.join(received)).find(
|
||||
(event) =>
|
||||
event.type === "turn_item.updated" &&
|
||||
event.turnItem.type === "dynamic_tool" &&
|
||||
event.turnItem.status === "completed",
|
||||
);
|
||||
assert.equal(statusReads, 2);
|
||||
assert.equal(
|
||||
completed?.type === "turn_item.updated" && completed.turnItem.title,
|
||||
"Edit remote document",
|
||||
);
|
||||
assert.deepEqual(completed?.type === "turn_item.updated" && completed.turnItem.toolSource, {
|
||||
key: "mcp:weather",
|
||||
name: "weather",
|
||||
kind: "integration",
|
||||
});
|
||||
if (failure === "timeout") assert.isTrue(signal?.aborted);
|
||||
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("admits a native command on its user receipt before generation completes", () =>
|
||||
Effect.gen(function* () {
|
||||
const nativeEvents = asyncEventStream();
|
||||
|
||||
@@ -383,6 +383,7 @@ function makeReplayClient(controller: OpenCodeReplayController): OpencodeClient
|
||||
reply: (input: unknown) => request("question.reply", input),
|
||||
},
|
||||
mcp: {
|
||||
status: () => request("mcp.status", {}),
|
||||
add: (input: unknown) => request("mcp.add", input),
|
||||
},
|
||||
} as unknown as OpencodeClient;
|
||||
|
||||
@@ -56,6 +56,7 @@ import * as Stream from "effect/Stream";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import { mcpToolPresentation } from "../../provider/McpToolPresentation.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger.ts";
|
||||
import * as ProviderEventLoggers from "../../provider/Layers/ProviderEventLoggers.ts";
|
||||
@@ -286,6 +287,7 @@ interface ActiveOpenCodeTurn {
|
||||
readonly parts: Map<string, Exclude<OpenCodePart, ToolPart>>;
|
||||
readonly partIdsByMessage: Map<string, Set<string>>;
|
||||
readonly toolNamesByCallId: Map<string, string>;
|
||||
mcpServerNames?: ReadonlyArray<string>;
|
||||
readonly providerTurn: OrchestrationV2ProviderTurn;
|
||||
nextItemOrdinal: number;
|
||||
nativeUserMessageId: string | null;
|
||||
@@ -1593,12 +1595,48 @@ export function makeOpenCodeAdapterV2(
|
||||
| "completedAt"
|
||||
| "updatedAt"
|
||||
>;
|
||||
const turnItem = openCodeToolTurnItem(base, {
|
||||
name: part.tool,
|
||||
input: toolInput(part),
|
||||
output: toolOutput(part),
|
||||
completedMetadata: part.state.status === "completed" ? part.state.metadata : undefined,
|
||||
});
|
||||
const input = toolInput(part);
|
||||
const output = toolOutput(part);
|
||||
const isNativeTool = part.tool === "code_search" || part.tool === "apply_patch";
|
||||
if (!isNativeTool && part.tool.includes("_") && turn.mcpServerNames === undefined) {
|
||||
const serverNames = yield* OpenCodeRuntime.runOpenCodeSdk("mcp.status", (signal) =>
|
||||
client.mcp.status(undefined, { signal, throwOnError: true }),
|
||||
).pipe(
|
||||
Effect.timeout("1 second"),
|
||||
Effect.map((response) => Object.keys(response.data ?? {})),
|
||||
Effect.catch(() => Effect.succeed(undefined)),
|
||||
);
|
||||
if (serverNames !== undefined) turn.mcpServerNames = serverNames;
|
||||
}
|
||||
const matchingServers = turn.mcpServerNames?.filter(
|
||||
(name) =>
|
||||
!isNativeTool && part.tool.startsWith(`${name.replace(/[^a-zA-Z0-9_-]/g, "_")}_`),
|
||||
);
|
||||
const serverName = matchingServers?.length === 1 ? matchingServers[0] : undefined;
|
||||
const presentation =
|
||||
serverName === undefined
|
||||
? {}
|
||||
: mcpToolPresentation({
|
||||
serverName,
|
||||
toolName: part.tool.slice(serverName.replace(/[^a-zA-Z0-9_-]/g, "_").length + 1),
|
||||
title: toolTitle(part) === part.tool ? undefined : toolTitle(part),
|
||||
});
|
||||
const turnItem: OrchestrationV2TurnItem = matchingServers?.length
|
||||
? {
|
||||
...base,
|
||||
type: "dynamic_tool",
|
||||
...presentation,
|
||||
toolName: part.tool,
|
||||
input,
|
||||
...(output === undefined ? {} : { output }),
|
||||
}
|
||||
: openCodeToolTurnItem(base, {
|
||||
name: part.tool,
|
||||
input,
|
||||
output,
|
||||
completedMetadata:
|
||||
part.state.status === "completed" ? part.state.metadata : undefined,
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "node.updated",
|
||||
driver: OPENCODE_PROVIDER,
|
||||
|
||||
@@ -1063,6 +1063,47 @@ describe("PiAdapterV2", () => {
|
||||
}).pipe(Effect.scoped, Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("presents explicitly namespaced MCP extension tools", () =>
|
||||
Effect.gen(function* () {
|
||||
const fake = yield* makeFakePi;
|
||||
const { runtime, takeEvent } = yield* openRuntime(fake);
|
||||
const providerThread = yield* runtime.ensureThread({
|
||||
threadId: THREAD_ID,
|
||||
modelSelection: modelSelection("default"),
|
||||
runtimePolicy,
|
||||
});
|
||||
yield* startTurn(runtime, providerThread);
|
||||
yield* fake.takeRequest("prompt");
|
||||
yield* fake.emit({ type: "agent_start" });
|
||||
for (const type of ["tool_execution_start", "tool_execution_end"]) {
|
||||
yield* fake.emit({
|
||||
type,
|
||||
toolCallId: "weather-call",
|
||||
toolName: "mcp__weather__get_weather",
|
||||
args: { city: "Berlin" },
|
||||
result: { content: [{ type: "text", text: "Sunny" }] },
|
||||
isError: false,
|
||||
});
|
||||
const event = yield* takeEvent(
|
||||
(event) => event.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool",
|
||||
);
|
||||
if (event.type !== "turn_item.updated" || event.turnItem.type !== "dynamic_tool")
|
||||
return yield* Effect.die("Expected an MCP tool item");
|
||||
assert.equal(event.turnItem.title, "get weather");
|
||||
assert.equal(
|
||||
event.turnItem.status,
|
||||
type === "tool_execution_start" ? "running" : "completed",
|
||||
);
|
||||
assert.deepEqual(event.turnItem.toolSource, {
|
||||
key: "mcp:weather",
|
||||
name: "weather",
|
||||
kind: "integration",
|
||||
});
|
||||
assert.deepEqual(event.turnItem.input, { city: "Berlin" });
|
||||
}
|
||||
}).pipe(Effect.scoped, Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("observes official subagent results without inventing child threads", () =>
|
||||
Effect.gen(function* () {
|
||||
const fake = yield* makeFakePi;
|
||||
|
||||
@@ -61,6 +61,7 @@ import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import { mcpToolPresentation } from "../../provider/McpToolPresentation.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import {
|
||||
expandPiSkillReference,
|
||||
@@ -1016,6 +1017,7 @@ export function makePiAdapterV2(
|
||||
...shared,
|
||||
title: toolName,
|
||||
type: "dynamic_tool",
|
||||
...mcpToolPresentation({ toolName }),
|
||||
toolName,
|
||||
input: args ?? {},
|
||||
...(outputText.length > 0 ? { output: outputText } : {}),
|
||||
|
||||
+7
-2
@@ -35,6 +35,7 @@ export function assertClaudeMcpToolPresentationOutput(
|
||||
|
||||
assert.equal(scrape?.status, "completed");
|
||||
assert.equal(scrape?.title, "Firecrawl scrape");
|
||||
assert.deepEqual(scrape?.toolIcon, scrape?.toolSource?.icon);
|
||||
assert.deepEqual(scrape?.toolSource, {
|
||||
key: "mcp:firecrawl",
|
||||
name: "Firecrawl",
|
||||
@@ -46,6 +47,10 @@ export function assertClaudeMcpToolPresentationOutput(
|
||||
});
|
||||
|
||||
assert.equal(map?.status, "completed");
|
||||
assert.isNull(map?.title);
|
||||
assert.notProperty(map, "toolSource");
|
||||
assert.equal(map?.title, "firecrawl map");
|
||||
assert.deepEqual(map?.toolSource, {
|
||||
key: "mcp:firecrawl",
|
||||
name: "Firecrawl",
|
||||
kind: "integration",
|
||||
});
|
||||
}
|
||||
@@ -6,25 +6,18 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import type * as EffectCodexSchema from "effect-codex-app-server/schema";
|
||||
|
||||
import {
|
||||
mcpToolPresentation as integrationToolPresentation,
|
||||
normalizeMcpHttpUrl as normalizedHttpUrl,
|
||||
normalizeMcpText as normalizedDisplayName,
|
||||
} from "./McpToolPresentation.ts";
|
||||
|
||||
type CodexLifecycleItem = EffectCodexSchema.V2ItemCompletedNotification["item"];
|
||||
|
||||
function asUnknownRecord(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
|
||||
}
|
||||
|
||||
function normalizedHttpUrl(value: unknown): string | undefined {
|
||||
if (typeof value !== "string" || value.length > 4096) return undefined;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
const href = url.href;
|
||||
return (url.protocol === "http:" || url.protocol === "https:") && href.length <= 4096
|
||||
? href
|
||||
: undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizedImageUrl(value: unknown): string | undefined {
|
||||
if (typeof value !== "string" || value.length > 4096) return undefined;
|
||||
try {
|
||||
@@ -45,12 +38,6 @@ function normalizedAppId(value: unknown): string | undefined {
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function normalizedDisplayName(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") return undefined;
|
||||
const displayName = value.trim().replace(/\s+/gu, " ");
|
||||
return displayName && displayName.length <= 160 ? displayName : undefined;
|
||||
}
|
||||
|
||||
function normalizedSourceKeyPart(value: string): string {
|
||||
return value.trim().toLowerCase();
|
||||
}
|
||||
@@ -130,6 +117,7 @@ function themedLogoIcon(
|
||||
}
|
||||
|
||||
export interface McpToolPresentation {
|
||||
readonly title?: string;
|
||||
readonly toolSurface?: "browser" | "computer";
|
||||
readonly toolIcon?: ToolActivityIcon;
|
||||
readonly toolSource?: ToolActivitySource;
|
||||
@@ -227,5 +215,13 @@ export function mcpToolPresentation(
|
||||
};
|
||||
}
|
||||
|
||||
return {};
|
||||
return integrationToolPresentation({
|
||||
serverName: appContext?.connectorId ?? item.server,
|
||||
toolName: item.tool,
|
||||
title: appContext?.actionName,
|
||||
serverDisplayName: appContext?.appName,
|
||||
source: sourceMetadata,
|
||||
iconUrl: sourceLogo?._tag === "themed-logo" ? sourceLogo.logoUrl : undefined,
|
||||
iconUrlDark: sourceLogo?._tag === "themed-logo" ? sourceLogo.logoUrlDark : undefined,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { mcpToolPresentation } from "./McpToolPresentation.ts";
|
||||
|
||||
describe("mcpToolPresentation", () => {
|
||||
it("uses supplied names and logos while retaining the server identity", () => {
|
||||
expect(
|
||||
mcpToolPresentation({
|
||||
serverName: "firecrawl-local",
|
||||
toolName: "firecrawl_scrape",
|
||||
title: " Scrape\n page ",
|
||||
serverDisplayName: "Firecrawl",
|
||||
iconUrl: "https://example.com/icon.png",
|
||||
iconUrlDark: "https://example.com/dark.png",
|
||||
}),
|
||||
).toEqual({
|
||||
title: "Scrape page",
|
||||
toolIcon: {
|
||||
_tag: "themed-logo",
|
||||
logoUrl: "https://example.com/icon.png",
|
||||
logoUrlDark: "https://example.com/dark.png",
|
||||
},
|
||||
toolSource: {
|
||||
key: "mcp:firecrawl-local",
|
||||
name: "Firecrawl",
|
||||
kind: "integration",
|
||||
icon: {
|
||||
_tag: "themed-logo",
|
||||
logoUrl: "https://example.com/icon.png",
|
||||
logoUrlDark: "https://example.com/dark.png",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("uses MCP result source metadata for the tool and its integration", () => {
|
||||
const presentation = mcpToolPresentation({
|
||||
serverName: "firecrawl-local",
|
||||
toolName: "firecrawl_scrape",
|
||||
source: {
|
||||
name: "Firecrawl",
|
||||
logoUrl: "https://example.com/firecrawl.png",
|
||||
logoUrlDark: "https://example.com/firecrawl-dark.png",
|
||||
},
|
||||
});
|
||||
expect(presentation.toolSource?.name).toBe("Firecrawl");
|
||||
expect(presentation.toolIcon).toEqual({
|
||||
_tag: "themed-logo",
|
||||
logoUrl: "https://example.com/firecrawl.png",
|
||||
logoUrlDark: "https://example.com/firecrawl-dark.png",
|
||||
});
|
||||
expect(presentation.toolSource?.icon).toEqual(presentation.toolIcon);
|
||||
});
|
||||
|
||||
it("uses readable fallback names without a guessed logo", () => {
|
||||
expect(mcpToolPresentation({ toolName: "mcp__my_server__get_weather" })).toEqual({
|
||||
title: "get weather",
|
||||
toolSource: { key: "mcp:my_server", name: "my server", kind: "integration" },
|
||||
});
|
||||
expect(mcpToolPresentation({ toolName: "Read" })).toEqual({});
|
||||
expect(mcpToolPresentation({ serverName: "t3-code", toolName: "delegate_task" })).toEqual({});
|
||||
});
|
||||
|
||||
it.each([
|
||||
"javascript:alert(1)",
|
||||
"file:///tmp/logo.png",
|
||||
"not a URL",
|
||||
"https://example.com/" + "x".repeat(4096),
|
||||
])("ignores an invalid logo %s", (iconUrl) => {
|
||||
expect(
|
||||
mcpToolPresentation({
|
||||
serverName: "weather",
|
||||
toolName: "get_weather",
|
||||
iconUrl,
|
||||
title: "x".repeat(161),
|
||||
}),
|
||||
).toEqual({
|
||||
title: "get weather",
|
||||
toolSource: { key: "mcp:weather", name: "weather", kind: "integration" },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects malformed and overlong names", () => {
|
||||
expect(mcpToolPresentation({ serverName: {}, toolName: 1, title: [] })).toEqual({});
|
||||
expect(mcpToolPresentation({ serverName: "x".repeat(161), toolName: "get_weather" })).toEqual(
|
||||
{},
|
||||
);
|
||||
expect(mcpToolPresentation({ title: "Tool title" })).toEqual({ title: "Tool title" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
null,
|
||||
"logo",
|
||||
{ logoUrl: "file:///tmp/logo.png" },
|
||||
{ logoUrlDark: "https://example.com/dark.png" },
|
||||
])("ignores source metadata without a valid logo: %j", (source) => {
|
||||
expect(mcpToolPresentation({ serverName: "weather", toolName: "get_weather", source })).toEqual(
|
||||
{
|
||||
title: "get weather",
|
||||
toolSource: { key: "mcp:weather", name: "weather", kind: "integration" },
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import type { ToolActivityIcon, ToolActivitySource } from "@t3tools/contracts";
|
||||
import { resolveT3McpToolDefinition } from "@t3tools/shared/t3McpToolPresentation";
|
||||
|
||||
export function normalizeMcpText(value: unknown, maxLength = 160): string | undefined {
|
||||
if (typeof value !== "string") return undefined;
|
||||
const text = value.trim().replace(/\s+/gu, " ");
|
||||
return text.length > 0 && text.length <= maxLength ? text : undefined;
|
||||
}
|
||||
|
||||
export function normalizeMcpHttpUrl(value: unknown): string | undefined {
|
||||
if (typeof value !== "string" || value.length > 4096) return undefined;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return (url.protocol === "https:" || url.protocol === "http:") && url.href.length <= 4096
|
||||
? url.href
|
||||
: undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function mcpToolPresentation(input: {
|
||||
readonly toolName?: unknown;
|
||||
readonly serverName?: unknown;
|
||||
readonly title?: unknown;
|
||||
readonly serverDisplayName?: unknown;
|
||||
readonly iconUrl?: unknown;
|
||||
readonly iconUrlDark?: unknown;
|
||||
readonly source?: unknown;
|
||||
}): {
|
||||
readonly title?: string;
|
||||
readonly toolIcon?: ToolActivityIcon;
|
||||
readonly toolSource?: ToolActivitySource;
|
||||
} {
|
||||
const source =
|
||||
typeof input.source === "object" && input.source !== null ? input.source : undefined;
|
||||
const qualified =
|
||||
typeof input.toolName === "string" ? /^mcp__(.+?)__(.+)$/i.exec(input.toolName) : null;
|
||||
const server = normalizeMcpText(input.serverName ?? qualified?.[1] ?? input.serverDisplayName);
|
||||
const tool = normalizeMcpText(qualified?.[2] ?? input.toolName);
|
||||
if (server && tool && resolveT3McpToolDefinition(`${server}.${tool}`)) return {};
|
||||
const title =
|
||||
normalizeMcpText(input.title) ??
|
||||
(server && tool ? normalizeMcpText(tool.replace(/[_-]+/gu, " ")) : undefined);
|
||||
if (!server) return title ? { title } : {};
|
||||
const name =
|
||||
normalizeMcpText(input.serverDisplayName) ??
|
||||
normalizeMcpText(source && Reflect.get(source, "name")) ??
|
||||
normalizeMcpText(server.replace(/[_-]+/gu, " ")) ??
|
||||
server;
|
||||
const logoUrl =
|
||||
normalizeMcpHttpUrl(input.iconUrl) ??
|
||||
normalizeMcpHttpUrl(source && Reflect.get(source, "logoUrl"));
|
||||
const logoUrlDark =
|
||||
normalizeMcpHttpUrl(input.iconUrlDark) ??
|
||||
normalizeMcpHttpUrl(source && Reflect.get(source, "logoUrlDark"));
|
||||
const icon = logoUrl
|
||||
? { _tag: "themed-logo" as const, logoUrl, ...(logoUrlDark ? { logoUrlDark } : {}) }
|
||||
: undefined;
|
||||
return {
|
||||
...(title ? { title } : {}),
|
||||
...(icon ? { toolIcon: icon } : {}),
|
||||
toolSource: {
|
||||
key: `mcp:${server.toLowerCase()}`,
|
||||
name,
|
||||
kind: "integration",
|
||||
...(icon ? { icon } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1539,9 +1539,44 @@ describe("extractMcpToolCallIdentity", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("does not brand tools whose meta asserts a foreign server", () => {
|
||||
// The foreign assertion vetoes every loose source, including a title
|
||||
// that would otherwise match a T3 convention.
|
||||
it.each([
|
||||
{ _meta: { claudeCode: { toolName: "mcp__weather__get_weather" } } },
|
||||
{ _meta: { toolName: "mcp::weather::get_weather", serverId: "weather" } },
|
||||
])("recovers external MCP identity from provider metadata", (metadata) => {
|
||||
const toolCall = toolCallFromUpdate({
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "weather-call",
|
||||
title: "Checking the forecast",
|
||||
status: "in_progress",
|
||||
...metadata,
|
||||
});
|
||||
expect(extractMcpToolCallIdentity(toolCall)).toEqual({
|
||||
server: "weather",
|
||||
tool: "get_weather",
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ kind: "execute", toolName: "developer__shell", extensionName: "developer" },
|
||||
{ kind: "edit", toolName: "developer__edit", extensionName: "developer" },
|
||||
{ kind: "other", toolName: "weather__get_weather", extensionName: "weather" },
|
||||
] as const)(
|
||||
"leaves goose $toolName unclassified so built-ins keep their projection",
|
||||
({ kind, toolName, extensionName }) => {
|
||||
// goose tags built-in extensions exactly like user MCP servers.
|
||||
const toolCall = toolCallFromUpdate({
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "goose-builtin",
|
||||
kind,
|
||||
title: "developer: shell",
|
||||
status: "in_progress",
|
||||
_meta: { goose: { toolCall: { toolName, extensionName } } },
|
||||
});
|
||||
expect(extractMcpToolCallIdentity(toolCall)).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
it("uses the asserted server instead of a misleading T3 title", () => {
|
||||
const toolCall = toolCallFromUpdate({
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "foreign-1",
|
||||
@@ -1551,7 +1586,10 @@ describe("extractMcpToolCallIdentity", () => {
|
||||
_meta: { toolName: "delegate_task", serverId: "other-orchestrator" },
|
||||
});
|
||||
|
||||
expect(extractMcpToolCallIdentity(toolCall)).toBeUndefined();
|
||||
expect(extractMcpToolCallIdentity(toolCall)).toEqual({
|
||||
server: "other-orchestrator",
|
||||
tool: "delegate_task",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not brand path-like or unknown-tool titles", () => {
|
||||
|
||||
@@ -1134,9 +1134,7 @@ export function extractMcpToolCallIdentity(
|
||||
// (goose, qwen, claude-acp) or only through the namespaced function name
|
||||
// in the title. The verbatim wire title survives merges even when a later
|
||||
// titleless or LLM-enriched update replaces the presentation title, so
|
||||
// match those rather than the summarized state title. Name-derived matches
|
||||
// are gated on the known T3 tool inventory so path-like titles (for
|
||||
// example "t3-code/README.md") never brand.
|
||||
// match those rather than the summarized state title.
|
||||
const claudeCode = isRecord(meta?.claudeCode) ? meta.claudeCode : undefined;
|
||||
const gooseToolCall = isRecord(meta?.goose)
|
||||
? isRecord(meta.goose.toolCall)
|
||||
@@ -1160,15 +1158,22 @@ export function extractMcpToolCallIdentity(
|
||||
}
|
||||
}
|
||||
}
|
||||
// A present-but-foreign origin assertion marks the whole call as another
|
||||
// server's MCP call, so no loose name matching (meta or title) may brand it.
|
||||
const gooseExtension =
|
||||
typeof gooseToolCall?.extensionName === "string" ? gooseToolCall.extensionName.trim() : "";
|
||||
const assertsForeignOrigin =
|
||||
(metaServerId.length > 0 && !/^t3[-_ ]?code$/i.test(metaServerId)) ||
|
||||
(gooseExtension.length > 0 && !/^t3[-_ ]?code$/i.test(gooseExtension));
|
||||
// A foreign origin never brands as T3. qwen's serverId marks a real MCP
|
||||
// server, but goose reports its built-in extensions (developer__shell,
|
||||
// edits) the same way as user MCP servers, so goose stays unclassified and
|
||||
// keeps its command and file-change projections.
|
||||
if (assertsForeignOrigin) {
|
||||
return undefined;
|
||||
if (metaServerId.length === 0 || metaToolName.length === 0) return undefined;
|
||||
const prefix = [`mcp__${metaServerId}__`, `mcp::${metaServerId}::`].find((prefix) =>
|
||||
metaToolName.startsWith(prefix),
|
||||
);
|
||||
const tool = prefix === undefined ? metaToolName : metaToolName.slice(prefix.length);
|
||||
return tool ? { server: metaServerId, tool } : undefined;
|
||||
}
|
||||
const candidates = [
|
||||
meta?.toolName,
|
||||
@@ -1178,6 +1183,9 @@ export function extractMcpToolCallIdentity(
|
||||
].filter((value): value is string => typeof value === "string");
|
||||
for (const candidate of candidates) {
|
||||
const trimmed = candidate.trim();
|
||||
const qualified = /^mcp__(.+?)__(.+)$/i.exec(trimmed);
|
||||
if (qualified?.[1] && qualified[2] && !/^t3[-_ ]?code$/i.test(qualified[1]))
|
||||
return { server: qualified[1], tool: qualified[2] };
|
||||
const match =
|
||||
T3_MCP_TITLE_CALL.exec(trimmed) ??
|
||||
T3_MCP_TITLE_SUFFIX_CALL.exec(trimmed) ??
|
||||
|
||||
Reference in new issue
Block a user