Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: support run client tools in agent gateway mode (#13792)

Arvin Xuc70ac84da7f1
diff --git a/src/libs/agent-stream/client.test.ts b/src/libs/agent-stream/client.test.ts
index c14002d2254..6c11c033098 100644
--- a/src/libs/agent-stream/client.test.ts
+++ b/src/libs/agent-stream/client.test.ts
@@ -401,6 +401,60 @@ describe('AgentStreamClient', () => {
});
});
+ describe('sendToolResult', () => {
+ it('should send a successful tool_result message', async () => {
+ const client = createClient();
+ const ws = await connectAndAuth(client);
+
+ const ok = client.sendToolResult({
+ content: '{"files":["a.txt"]}',
+ success: true,
+ toolCallId: 'call_1',
+ });
+
+ expect(ok).toBe(true);
+ const toolResult = ws.sent.find((s) => JSON.parse(s).type === 'tool_result');
+ expect(toolResult).toBeDefined();
+ expect(JSON.parse(toolResult!)).toEqual({
+ content: '{"files":["a.txt"]}',
+ success: true,
+ toolCallId: 'call_1',
+ type: 'tool_result',
+ });
+ });
+
+ it('should send an error tool_result message', async () => {
+ const client = createClient();
+ const ws = await connectAndAuth(client);
+
+ client.sendToolResult({
+ content: null,
+ error: { message: 'ipc failed', type: 'ipc_error' },
+ success: false,
+ toolCallId: 'call_2',
+ });
+
+ const toolResult = ws.sent.find((s) => JSON.parse(s).type === 'tool_result');
+ expect(JSON.parse(toolResult!)).toEqual({
+ content: null,
+ error: { message: 'ipc failed', type: 'ipc_error' },
+ success: false,
+ toolCallId: 'call_2',
+ type: 'tool_result',
+ });
+ });
+
+ it('should return false when socket is not open', () => {
+ const client = createClient();
+ const ok = client.sendToolResult({
+ content: null,
+ success: false,
+ toolCallId: 'call_3',
+ });
+ expect(ok).toBe(false);
+ });
+ });
+
describe('disconnect', () => {
it('should clean up timers on disconnect', async () => {
const client = createClient();
diff --git a/src/libs/agent-stream/client.ts b/src/libs/agent-stream/client.ts
index 6f3445e728d..6eb9db5b7f9 100644
--- a/src/libs/agent-stream/client.ts
+++ b/src/libs/agent-stream/client.ts
@@ -5,6 +5,7 @@ import type {
ClientMessage,
ConnectionStatus,
ServerMessage,
+ ToolResultMessage,
} from './types';
// ─── Constants ───
@@ -146,6 +147,16 @@ export class AgentStreamClient extends TypedEmitter {
this.sendMessage({ type: 'interrupt' });
}
+ /**
+ * Send a tool execution result back to the server.
+ * Correlated by toolCallId; the server's agent loop is blocked on BLPOP until this arrives.
+ * Returns true when the payload was handed off to the WebSocket, false when no live socket
+ * is available (caller should fall back to server-side BLPOP timeout).
+ */
+ sendToolResult(result: Omit<ToolResultMessage, 'type'>): boolean {
+ return this.sendMessage({ ...result, type: 'tool_result' });
+ }
+
/**
* Update the auth token (e.g. after JWT refresh). Call connect() or wait for auto-reconnect.
*/
@@ -418,10 +429,12 @@ export class AgentStreamClient extends TypedEmitter {
// ─── Helpers ───
- private sendMessage(data: ClientMessage): void {
+ private sendMessage(data: ClientMessage): boolean {
if (this.ws?.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(data));
+ return true;
}
+ return false;
}
private closeWebSocket(): void {
diff --git a/src/libs/agent-stream/index.ts b/src/libs/agent-stream/index.ts
index d4529157aae..9467593c068 100644
--- a/src/libs/agent-stream/index.ts
+++ b/src/libs/agent-stream/index.ts
@@ -10,5 +10,7 @@ export type {
StreamChunkType,
StreamStartData,
ToolEndData,
+ ToolExecuteData,
+ ToolResultMessage,
ToolStartData,
} from './types';
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index 40351f4ba69..a0f16efc7fb 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -14,6 +14,12 @@ export interface ExecAgentTaskParams {
topicId?: string | null;
};
autoStart?: boolean;
+ /**
+ * Runtime of the client initiating this request. When 'desktop', server
+ * enables `executor: 'client'` tools (local-system, stdio MCP) and
+ * dispatches them over the Agent Gateway WS back to this client.
+ */
+ clientRuntime?: 'desktop' | 'web';
deviceId?: string;
existingMessageIds?: string[];
/** File IDs of already-uploaded attachments to attach to the new user message */
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/clientToolExecution.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/clientToolExecution.test.ts
new file mode 100644
index 00000000000..b0bf943b233
--- /dev/null
+++ b/src/store/chat/slices/aiChat/actions/__tests__/clientToolExecution.test.ts
@@ -0,0 +1,305 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ToolExecuteData } from '@/libs/agent-stream';
+
+import { ClientToolExecutionActionImpl } from '../clientToolExecution';
+
+// ─── Hoisted mocks ───
+
+const { hasExecutorMock, invokeExecutorMock, invokeMcpToolCallMock } = vi.hoisted(() => ({
+ hasExecutorMock: vi.fn(),
+ invokeExecutorMock: vi.fn(),
+ invokeMcpToolCallMock: vi.fn(),
+}));
+
+vi.mock('@/store/tool/slices/builtin/executors', () => ({
+ hasExecutor: hasExecutorMock,
+ invokeExecutor: invokeExecutorMock,
+}));
+
+vi.mock('@/services/mcp', () => ({
+ mcpService: {
+ invokeMcpToolCall: invokeMcpToolCallMock,
+ },
+}));
+
+// ─── Shared harness ───
+
+function makeData(overrides: Partial<ToolExecuteData> = {}): ToolExecuteData {
+ return {
+ apiName: 'readFile',
+ arguments: '{"path":"/tmp/a.txt"}',
+ executionTimeoutMs: 60_000,
+ identifier: 'local-system',
+ toolCallId: 'call_1',
+ ...overrides,
+ };
+}
+
+function setup(options: { hasConnection?: boolean; sendReturns?: boolean } = {}) {
+ const { hasConnection = true, sendReturns = true } = options;
+
+ const sendToolResult = vi.fn(() => sendReturns);
+
+ const state: any = {
+ gatewayConnections: hasConnection
+ ? {
+ 'op-1': {
+ client: {
+ connect: vi.fn(),
+ disconnect: vi.fn(),
+ on: vi.fn(),
+ sendInterrupt: vi.fn(),
+ sendToolResult,
+ },
+ status: 'connected',
+ },
+ }
+ : {},
+ operations: {
+ 'op-1': {
+ abortController: { signal: { aborted: false } },
+ context: { agentId: 'agent-1', topicId: 'topic-1' },
+ },
+ },
+ pendingClientToolExecutions: {},
+ };
+
+ const set = vi.fn((updater: any) => {
+ const patch = typeof updater === 'function' ? updater(state) : updater;
+ Object.assign(state, patch);
+ });
+ const get = vi.fn(() => state);
+
+ const action = new ClientToolExecutionActionImpl(set, get);
+ return { action, sendToolResult, state, set, get };
+}
+
+beforeEach(() => {
+ hasExecutorMock.mockReset();
+ invokeExecutorMock.mockReset();
+ invokeMcpToolCallMock.mockReset();
+});
+
+// ─── Tests ───
+
+describe('internal_executeClientTool', () => {
+ describe('builtin dispatch', () => {
+ it('sends a successful tool_result when the executor returns content', async () => {
+ hasExecutorMock.mockReturnValue(true);
+ invokeExecutorMock.mockResolvedValue({
+ content: 'files: a.txt',
+ state: { lastDir: '/tmp' },
+ success: true,
+ });
+ const { action, sendToolResult } = setup();
+
+ await action.internal_executeClientTool(makeData(), { operationId: 'op-1' });
+
+ expect(invokeExecutorMock).toHaveBeenCalledWith(
+ 'local-system',
+ 'readFile',
+ { path: '/tmp/a.txt' },
+ expect.objectContaining({
+ agentId: 'agent-1',
+ messageId: 'call_1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ }),
+ );
+ expect(sendToolResult).toHaveBeenCalledWith({
+ content: 'files: a.txt',
+ state: { lastDir: '/tmp' },
+ success: true,
+ toolCallId: 'call_1',
+ });
+ });
+
+ it('sends a failure tool_result when the executor reports error', async () => {
+ hasExecutorMock.mockReturnValue(true);
+ invokeExecutorMock.mockResolvedValue({
+ error: { message: 'ENOENT', type: 'fs_error' },
+ success: false,
+ });
+ const { action, sendToolResult } = setup();
+
+ await action.internal_executeClientTool(makeData(), { operationId: 'op-1' });
+
+ expect(sendToolResult).toHaveBeenCalledWith({
+ content: 'ENOENT',
+ error: { message: 'ENOENT', type: 'fs_error' },
+ state: undefined,
+ success: false,
+ toolCallId: 'call_1',
+ });
+ });
+
+ it('passes {} to executor when arguments is empty', async () => {
+ hasExecutorMock.mockReturnValue(true);
+ invokeExecutorMock.mockResolvedValue({ content: 'ok', success: true });
+ const { action } = setup();
+
+ await action.internal_executeClientTool(makeData({ arguments: '' }), {
+ operationId: 'op-1',
+ });
+
+ expect(invokeExecutorMock).toHaveBeenCalledWith(
+ 'local-system',
+ 'readFile',
+ {},
+ expect.anything(),
+ );
+ });
+ });
+
+ describe('error paths never block the server', () => {
+ it('sends tool_result with parse error when arguments are malformed', async () => {
+ hasExecutorMock.mockReturnValue(true);
+ const { action, sendToolResult } = setup();
+
+ await action.internal_executeClientTool(makeData({ arguments: '{not-json' }), {
+ operationId: 'op-1',
+ });
+
+ expect(invokeExecutorMock).not.toHaveBeenCalled();
+ expect(sendToolResult).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: null,
+ error: expect.objectContaining({ type: 'arguments_parse_error' }),
+ success: false,
+ toolCallId: 'call_1',
+ }),
+ );
+ });
+
+ it('sends tool_result when invokeExecutor throws', async () => {
+ hasExecutorMock.mockReturnValue(true);
+ invokeExecutorMock.mockRejectedValue(new Error('ipc died'));
+ const { action, sendToolResult } = setup();
+
+ await action.internal_executeClientTool(makeData(), { operationId: 'op-1' });
+
+ expect(sendToolResult).toHaveBeenCalledWith(
+ expect.objectContaining({
+ error: expect.objectContaining({
+ message: 'ipc died',
+ type: 'client_tool_execution_error',
+ }),
+ success: false,
+ toolCallId: 'call_1',
+ }),
+ );
+ });
+
+ it('sends a not-found tool_result when no executor matches and MCP returns nothing', async () => {
+ hasExecutorMock.mockReturnValue(false);
+ invokeMcpToolCallMock.mockResolvedValue(undefined);
+ const { action, sendToolResult } = setup();
+
+ await action.internal_executeClientTool(makeData({ identifier: 'unknown-tool' }), {
+ operationId: 'op-1',
+ });
+
+ expect(sendToolResult).toHaveBeenCalledWith(
+ expect.objectContaining({
+ error: expect.objectContaining({ type: 'executor_not_found' }),
+ success: false,
+ }),
+ );
+ });
+
+ it('does not throw when gateway connection is missing (server will timeout)', async () => {
+ hasExecutorMock.mockReturnValue(true);
+ invokeExecutorMock.mockResolvedValue({ content: 'ok', success: true });
+ const { action, state } = setup({ hasConnection: false });
+
+ await expect(
+ action.internal_executeClientTool(makeData(), { operationId: 'op-1' }),
+ ).resolves.toBeUndefined();
+
+ // Pending state was cleared even when send couldn't happen
+ expect(state.pendingClientToolExecutions).toEqual({});
+ });
+ });
+
+ describe('MCP fallback', () => {
+ it('routes to mcpService when no builtin executor registered', async () => {
+ hasExecutorMock.mockReturnValue(false);
+ invokeMcpToolCallMock.mockResolvedValue({
+ content: 'mcp-ok',
+ state: { cursor: 1 },
+ success: true,
+ });
+ const { action, sendToolResult } = setup();
+
+ await action.internal_executeClientTool(
+ makeData({ apiName: 'echo', identifier: 'mcp-demo' }),
+ { operationId: 'op-1' },
+ );
+
+ expect(invokeMcpToolCallMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ apiName: 'echo',
+ arguments: '{"path":"/tmp/a.txt"}',
+ identifier: 'mcp-demo',
+ }),
+ expect.objectContaining({ topicId: 'topic-1' }),
+ );
+ expect(sendToolResult).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: 'mcp-ok',
+ state: { cursor: 1 },
+ success: true,
+ toolCallId: 'call_1',
+ }),
+ );
+ });
+
+ it('sends failure tool_result when MCP returns an error result', async () => {
+ hasExecutorMock.mockReturnValue(false);
+ invokeMcpToolCallMock.mockResolvedValue({
+ content: null,
+ error: { message: 'mcp boom', type: 'mcp_error' },
+ success: false,
+ });
+ const { action, sendToolResult } = setup();
+
+ await action.internal_executeClientTool(makeData({ identifier: 'mcp-demo' }), {
+ operationId: 'op-1',
+ });
+
+ expect(sendToolResult).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: null,
+ error: expect.objectContaining({ message: 'mcp boom', type: 'mcp_error' }),
+ success: false,
+ }),
+ );
+ });
+ });
+
+ describe('pending state', () => {
+ it('marks the call pending during execution and clears it afterwards', async () => {
+ hasExecutorMock.mockReturnValue(true);
+ let resolver: (v: any) => void = () => {};
+ invokeExecutorMock.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolver = resolve;
+ }),
+ );
+ const { action, state } = setup();
+
+ const promise = action.internal_executeClientTool(makeData(), { operationId: 'op-1' });
+
+ // Between start and resolve: pending map has the id
+ await Promise.resolve();
+ expect(state.pendingClientToolExecutions).toEqual({ call_1: true });
+
+ resolver({ content: 'done', success: true });
+ await promise;
+
+ expect(state.pendingClientToolExecutions).toEqual({});
+ });
+ });
+});
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
index 13942d899af..5a9f98d3977 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
@@ -52,6 +52,7 @@ function createMockClient(): GatewayConnection['client'] & {
set.add(listener);
}),
sendInterrupt: vi.fn(),
+ sendToolResult: vi.fn(() => true),
};
}
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
index c084c1358c0..9019bd0b0b8 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
@@ -15,6 +15,7 @@ function createMockStore() {
associateMessageWithOperation: vi.fn(),
completeOperation: vi.fn(),
internal_dispatchMessage: vi.fn(),
+ internal_executeClientTool: vi.fn().mockResolvedValue(undefined),
internal_toggleToolCallingStreaming: vi.fn(),
replaceMessages: vi.fn(),
};
@@ -22,12 +23,13 @@ function createMockStore() {
function createHandler(
store: ReturnType<typeof createMockStore>,
- overrides?: { assistantMessageId?: string },
+ overrides?: { assistantMessageId?: string; gatewayOperationId?: string },
) {
const get = vi.fn(() => store) as any;
return createGatewayEventHandler(get, {
assistantMessageId: overrides?.assistantMessageId ?? 'msg-initial',
context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' } as any,
+ gatewayOperationId: overrides?.gatewayOperationId,
operationId: 'op-1',
});
}
@@ -197,6 +199,72 @@ describe('createGatewayEventHandler', () => {
});
});
+ describe('tool_execute', () => {
+ const toolExecuteData = {
+ apiName: 'readFile',
+ arguments: '{"path":"/tmp/a.txt"}',
+ executionTimeoutMs: 60_000,
+ identifier: 'local-system',
+ toolCallId: 'call_1',
+ };
+
+ it('forwards the payload to internal_executeClientTool with operationId', async () => {
+ const store = createMockStore();
+ const handler = createHandler(store);
+
+ handler(makeEvent('tool_execute', toolExecuteData));
+ await flush();
+
+ expect(store.internal_executeClientTool).toHaveBeenCalledWith(toolExecuteData, {
+ operationId: 'op-1',
+ });
+ });
+
+ it('uses gatewayOperationId (WS key) when distinct from local operationId', async () => {
+ // Locally the handler tracks `op-1` (used for message dispatch), but
+ // the Agent Gateway WS is keyed on the server-side id `gw-op-server`.
+ // The action must receive the latter so it can look up the live
+ // AgentStreamClient in `gatewayConnections` and reply with tool_result.
+ const store = createMockStore();
+ const handler = createHandler(store, { gatewayOperationId: 'gw-op-server' });
+
+ handler(makeEvent('tool_execute', toolExecuteData));
+ await flush();
+
+ expect(store.internal_executeClientTool).toHaveBeenCalledWith(toolExecuteData, {
+ operationId: 'gw-op-server',
+ });
+ });
+
+ it('is fire-and-forget β€” does not block the event pipeline', async () => {
+ const store = createMockStore();
+ // Simulate a slow tool execution that never resolves
+ store.internal_executeClientTool.mockImplementation(() => new Promise(() => {}));
+ const handler = createHandler(store);
+
+ handler(makeEvent('tool_execute', toolExecuteData));
+ // If the handler awaited the action, this subsequent stream_chunk would
+ // be queued behind the pending promise forever. We assert it still runs.
+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'hi' }));
+ await flush();
+
+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ value: { content: 'hi' } }),
+ expect.any(Object),
+ );
+ });
+
+ it('ignores tool_execute events without data', async () => {
+ const store = createMockStore();
+ const handler = createHandler(store);
+
+ handler(makeEvent('tool_execute'));
+ await flush();
+
+ expect(store.internal_executeClientTool).not.toHaveBeenCalled();
+ });
+ });
+
describe('tool_end', () => {
it('should refresh messages to pull tool results', async () => {
const store = createMockStore();
diff --git a/src/store/chat/slices/aiChat/actions/clientToolExecution.ts b/src/store/chat/slices/aiChat/actions/clientToolExecution.ts
new file mode 100644
index 00000000000..ac6c4aaf115
--- /dev/null
+++ b/src/store/chat/slices/aiChat/actions/clientToolExecution.ts
@@ -0,0 +1,213 @@
+import { type BuiltinToolContext } from '@lobechat/types';
+import debug from 'debug';
+import { produce } from 'immer';
+
+import { type ToolExecuteData, type ToolResultMessage } from '@/libs/agent-stream';
+import { mcpService } from '@/services/mcp';
+import { type ChatStore } from '@/store/chat/store';
+import { hasExecutor, invokeExecutor } from '@/store/tool/slices/builtin/executors';
+import { type StoreSetter } from '@/store/types';
+import { safeParseJSON } from '@/utils/safeParseJSON';
+
+const log = debug('lobe-store:client-tool-execution');
+
+type Setter = StoreSetter<ChatStore>;
+
+/**
+ * Executes a Gateway `tool_execute` request locally and always returns a
+ * `tool_result` β€” even on parse failure, missing executor, or thrown error.
+ *
+ * Never let the server-side BLPOP time out: the contract is that every
+ * `tool_execute` produces exactly one `tool_result` back over the same WS.
+ */
+export class ClientToolExecutionActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ internal_executeClientTool = async (
+ data: ToolExecuteData,
+ context: { operationId: string },
+ ): Promise<void> => {
+ const { toolCallId, identifier, apiName, arguments: argsString } = data;
+ const { operationId } = context;
+
+ log(
+ '[internal_executeClientTool] start toolCallId=%s identifier=%s apiName=%s op=%s',
+ toolCallId,
+ identifier,
+ apiName,
+ operationId,
+ );
+
+ this.#setPending(toolCallId, true);
+
+ // Captured once; must be the SAME connection that received the execute request.
+ const conn = this.#get().gatewayConnections[operationId];
+
+ const send = (payload: Omit<ToolResultMessage, 'type'>): void => {
+ this.#setPending(toolCallId, false);
+ if (!conn) {
+ log(
+ '[internal_executeClientTool] no gateway connection for op=%s toolCallId=%s β€” server will timeout',
+ operationId,
+ toolCallId,
+ );
+ return;
+ }
+ const ok = conn.client.sendToolResult(payload);
+ if (!ok) {
+ log(
+ '[internal_executeClientTool] sendToolResult returned false (socket closed) for toolCallId=%s',
+ toolCallId,
+ );
+ }
+ };
+
+ // ─── Parse arguments ───
+ let params: any = {};
+ if (argsString) {
+ const parsed = safeParseJSON(argsString);
+ if (parsed === undefined) {
+ send({
+ content: null,
+ error: {
+ message: `Failed to parse tool arguments: ${argsString.slice(0, 200)}`,
+ type: 'arguments_parse_error',
+ },
+ success: false,
+ toolCallId,
+ });
+ return;
+ }
+ params = parsed ?? {};
+ }
+
+ try {
+ // ─── Builtin dispatch (via registry) ───
+ if (hasExecutor(identifier, apiName)) {
+ const operation = this.#get().operations[operationId];
+ const ctx: BuiltinToolContext = {
+ agentId: operation?.context?.agentId,
+ groupId: operation?.context?.groupId,
+ // Gateway-side tool messages are persisted on the server; the client
+ // has no local message id, so reuse toolCallId as the context key.
+ messageId: toolCallId,
+ operationId,
+ signal: operation?.abortController?.signal,
+ topicId: operation?.context?.topicId ?? undefined,
+ };
+
+ const result = await invokeExecutor(identifier, apiName, params, ctx);
+
+ if (result.error) {
+ send({
+ content: result.content ?? result.error.message ?? null,
+ error: { message: result.error.message, type: result.error.type },
+ state: result.state,
+ success: false,
+ toolCallId,
+ });
+ } else {
+ send({
+ content: result.content ?? null,
+ state: result.state,
+ success: !!result.success,
+ toolCallId,
+ });
+ }
+ return;
+ }
+
+ // ─── MCP fallback β€” unified dispatch, mirrors invokeMCPTypePlugin shape ───
+ const operation = this.#get().operations[operationId];
+ const mcpResult = await mcpService
+ .invokeMcpToolCall(
+ {
+ apiName,
+ arguments: argsString,
+ id: toolCallId,
+ identifier,
+ type: 'default',
+ },
+ {
+ signal: operation?.abortController?.signal,
+ topicId: operation?.context?.topicId ?? undefined,
+ },
+ )
+ .catch((err) => {
+ log(
+ '[internal_executeClientTool] mcp invoke threw for %s/%s: %O',
+ identifier,
+ apiName,
+ err,
+ );
+ return undefined;
+ });
+
+ if (!mcpResult) {
+ send({
+ content: null,
+ error: {
+ message: `No client executor available for ${identifier}/${apiName}`,
+ type: 'executor_not_found',
+ },
+ success: false,
+ toolCallId,
+ });
+ return;
+ }
+
+ send({
+ content: mcpResult.content ?? null,
+ error: mcpResult.success
+ ? undefined
+ : {
+ message: (mcpResult.error as any)?.message ?? 'MCP tool call failed',
+ type: (mcpResult.error as any)?.type,
+ },
+ state: mcpResult.state,
+ success: !!mcpResult.success,
+ toolCallId,
+ });
+ } catch (error) {
+ const err = error as Error;
+ log('[internal_executeClientTool] unexpected error toolCallId=%s: %O', toolCallId, err);
+ send({
+ content: null,
+ error: {
+ message: err?.message || 'Unknown client tool execution error',
+ type: 'client_tool_execution_error',
+ },
+ success: false,
+ toolCallId,
+ });
+ }
+ };
+
+ #setPending = (toolCallId: string, pending: boolean): void => {
+ this.#set(
+ (state) => ({
+ pendingClientToolExecutions: produce(state.pendingClientToolExecutions, (draft) => {
+ if (pending) {
+ draft[toolCallId] = true;
+ } else {
+ delete draft[toolCallId];
+ }
+ }),
+ }),
+ false,
+ `pendingClientTool/${pending ? 'start' : 'end'}`,
+ );
+ };
+}
+
+export type ClientToolExecutionAction = Pick<
+ ClientToolExecutionActionImpl,
+ keyof ClientToolExecutionActionImpl
+>;
diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.ts
index 8df5a5a9573..9654b7c6049 100644
--- a/src/store/chat/slices/aiChat/actions/gateway.ts
+++ b/src/store/chat/slices/aiChat/actions/gateway.ts
@@ -1,5 +1,6 @@
import type { ConversationContext, ExecAgentResult } from '@lobechat/types';
+import { isDesktop } from '@/const/version';
import type {
AgentStreamClientOptions,
AgentStreamEvent,
@@ -20,7 +21,10 @@ type Setter = StoreSetter<ChatStore>;
// ─── Types ───
export interface GatewayConnection {
- client: Pick<AgentStreamClient, 'connect' | 'disconnect' | 'on' | 'sendInterrupt'>;
+ client: Pick<
+ AgentStreamClient,
+ 'connect' | 'disconnect' | 'on' | 'sendInterrupt' | 'sendToolResult'
+ >;
status: ConnectionStatus;
}
@@ -229,6 +233,10 @@ export class GatewayActionImpl {
threadId: context.threadId,
topicId: context.topicId,
},
+ // Tell the server this caller is a desktop Electron client so it can
+ // enable `executor: 'client'` tools (local-system, stdio MCP) and
+ // dispatch them back over the Agent Gateway WS.
+ clientRuntime: isDesktop ? 'desktop' : 'web',
fileIds,
parentMessageId,
prompt: message,
@@ -270,6 +278,9 @@ export class GatewayActionImpl {
const eventHandler = createGatewayEventHandler(this.#get, {
assistantMessageId: result.assistantMessageId,
context: execContext,
+ // Server-side operation id β€” needed for tool_result dispatch back over
+ // the same WS that gatewayConnections is keyed on.
+ gatewayOperationId: result.operationId,
operationId: gatewayOpId,
});
@@ -336,6 +347,9 @@ export class GatewayActionImpl {
const eventHandler = createGatewayEventHandler(this.#get, {
assistantMessageId,
context,
+ // Server-side operation id β€” needed for tool_result dispatch back over
+ // the same WS that gatewayConnections is keyed on.
+ gatewayOperationId: operationId,
operationId: gatewayOpId,
});
diff --git a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
index dd9560570fe..cf7c87e2df1 100644
--- a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
+++ b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
@@ -5,6 +5,7 @@ import type {
StepCompleteData,
StreamChunkData,
StreamStartData,
+ ToolExecuteData,
} from '@/libs/agent-stream';
import { messageService } from '@/services/message';
import type { ChatStore } from '@/store/chat/store';
@@ -37,10 +38,17 @@ export const createGatewayEventHandler = (
params: {
assistantMessageId: string;
context: ConversationContext;
+ /**
+ * Server-side operation id β€” used to look up the `AgentStreamClient` in
+ * `gatewayConnections` so we can `sendToolResult` back over the same WS.
+ * Defaults to `operationId` when the caller does not distinguish the two.
+ */
+ gatewayOperationId?: string;
operationId: string;
},
) => {
const { context, operationId } = params;
+ const gatewayOperationId = params.gatewayOperationId ?? operationId;
// Dispatch context β€” ensures internal_dispatchMessage resolves the correct messageMapKey
const dispatchContext = { operationId };
@@ -149,6 +157,21 @@ export const createGatewayEventHandler = (
break;
}
+ case 'tool_execute': {
+ // Fire-and-forget: the client-side tool may take a long time, and we
+ // must keep processing other events (stream_chunk, tool_end, etc.) on
+ // the same WebSocket. `internal_executeClientTool` guarantees it never
+ // throws and always sends exactly one `tool_result` back.
+ //
+ // Use `gatewayOperationId` (server-side id, the key under
+ // `gatewayConnections`) so the action can look up the WS to reply on
+ // β€” NOT the local `operationId` used for `dispatchContext`.
+ const data = event.data as ToolExecuteData | undefined;
+ if (!data) break;
+ void get().internal_executeClientTool(data, { operationId: gatewayOperationId });
+ break;
+ }
+
case 'tool_end': {
enqueue(async () => {
await fetchAndReplaceMessages(get, context).catch(console.error);
diff --git a/src/store/chat/slices/aiChat/actions/index.ts b/src/store/chat/slices/aiChat/actions/index.ts
index 1729bed5467..0255305b6b6 100644
--- a/src/store/chat/slices/aiChat/actions/index.ts
+++ b/src/store/chat/slices/aiChat/actions/index.ts
@@ -3,6 +3,8 @@ import { type StateCreator } from 'zustand/vanilla';
import { type ChatStore } from '@/store/chat/store';
import { flattenActions } from '@/store/utils/flattenActions';
+import { type ClientToolExecutionAction } from './clientToolExecution';
+import { ClientToolExecutionActionImpl } from './clientToolExecution';
import { type ConversationControlAction } from './conversationControl';
import { ConversationControlActionImpl } from './conversationControl';
import { type ConversationLifecycleAction } from './conversationLifecycle';
@@ -17,6 +19,7 @@ import { type StreamingStatesAction } from './streamingStates';
import { StreamingStatesActionImpl } from './streamingStates';
export type ChatAIChatAction = ChatMemoryAction &
+ ClientToolExecutionAction &
ConversationLifecycleAction &
ConversationControlAction &
GatewayAction &
@@ -35,6 +38,7 @@ export const chatAiChat: StateCreator<
) =>
flattenActions<ChatAIChatAction>([
new ChatMemoryActionImpl(...params),
+ new ClientToolExecutionActionImpl(...params),
new ConversationLifecycleActionImpl(...params),
new ConversationControlActionImpl(...params),
new GatewayActionImpl(...params),
diff --git a/src/store/chat/slices/aiChat/initialState.ts b/src/store/chat/slices/aiChat/initialState.ts
index 25e2ab814ce..f94140e9bae 100644
--- a/src/store/chat/slices/aiChat/initialState.ts
+++ b/src/store/chat/slices/aiChat/initialState.ts
@@ -9,6 +9,13 @@ export interface ChatAIChatState {
inputFiles: File[];
inputMessage: string;
mainInputEditor: ChatInputEditor | null;
+ /**
+ * Tool calls currently being executed locally on this client in response to
+ * a Gateway `tool_execute` event. Key is the toolCallId; value is `true` while
+ * pending. Kept separate from `toolCallingStreamIds` (LLM-side streaming) so
+ * UI can render a distinct "running on device" state.
+ */
+ pendingClientToolExecutions: Record<string, boolean>;
searchWorkflowLoadingIds: string[];
threadInputEditor: ChatInputEditor | null;
/**
@@ -22,6 +29,7 @@ export const initialAiChatState: ChatAIChatState = {
inputFiles: [],
inputMessage: '',
mainInputEditor: null,
+ pendingClientToolExecutions: {},
searchWorkflowLoadingIds: [],
threadInputEditor: null,
toolCallingStreamIds: {},