Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

✨ feat: Client-Executed Function Tools for the Responses API (#16078)

Alexey Korepanovcb52198b4499
diff --git a/api/server/controllers/agents/__tests__/responses.unit.spec.js b/api/server/controllers/agents/__tests__/responses.unit.spec.js
index 70f0e93754..0e7c655156 100644
--- a/api/server/controllers/agents/__tests__/responses.unit.spec.js
+++ b/api/server/controllers/agents/__tests__/responses.unit.spec.js
@@ -241,6 +241,13 @@ jest.mock('@librechat/api', () => ({
buildInitialToolSessions: jest.fn().mockReturnValue(mockInitialSessions),
applyContextToAgent: (...args) => mockApplyContextToAgent(...args),
buildRunToolSet: jest.fn().mockReturnValue(new Set()),
+ /** No fixture declares a caller-executed tool, so the handoff stays inert. */
+ createClientToolHandoff: jest.fn(({ agentDefinitions }) => ({
+ toolDefinitions: agentDefinitions,
+ appliedTools: [],
+ wrapRunStep: (delegate) => delegate,
+ wrapToolExecute: (delegate) => delegate,
+ })),
AgentRunEnvelopeError: MockAgentRunEnvelopeError,
createAgentRunEnvelope: (...args) => mockCreateAgentRunEnvelope(...args),
resolveConversationCodeEnvironmentDecision: ({
@@ -878,6 +885,28 @@ describe('createResponse controller', () => {
);
});
+ it.each([false, true])(
+ 'excludes caller-executed tools from eager execution: stream=%s',
+ async (stream) => {
+ const api = require('@librechat/api');
+ const clientToolNames = new Set(['submit_sql']);
+ api.validateResponseRequest.mockReturnValueOnce({
+ request: { model: 'agent-123', input: 'Hello', stream },
+ });
+ api.createClientToolHandoff.mockImplementationOnce(({ agentDefinitions }) => ({
+ toolDefinitions: agentDefinitions,
+ appliedTools: [],
+ clientToolNames,
+ wrapRunStep: (delegate) => delegate,
+ wrapToolExecute: (delegate) => delegate,
+ }));
+
+ await createResponse(req, res);
+
+ expect(api.createRun).toHaveBeenCalledWith(expect.objectContaining({ clientToolNames }));
+ },
+ );
+
it('invokes the graph with the resolved recursion limit rather than the SDK default', async () => {
const api = require('@librechat/api');
const processStream = jest.fn().mockResolvedValue(undefined);
diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.js
index 1b4772ffd0..f44a9c37c5 100644
--- a/api/server/controllers/agents/responses.js
+++ b/api/server/controllers/agents/responses.js
@@ -76,6 +76,7 @@ const {
sendResponsesErrorResponse,
createResponsesEventHandlers,
createAggregatorEventHandlers,
+ createClientToolHandoff,
getLangfuseTraceMessageFields,
stripActivityLabelParts,
stripUnusableSummaryParts,
@@ -1091,6 +1092,25 @@ const executeResponse = async (envelope, { req, res }) => {
// Merge previous messages with new input
const allMessages = [...previousMessages, ...inputMessages];
+ /** The caller's function tools: declared to the model with no server-side
+ * executor, handed back when the model calls one, and reported on the
+ * response as the subset that was actually applied.
+ *
+ * Built once every agent of the run is known, because the interception
+ * matches on tool name across the whole graph: a name a subagent owns
+ * collides exactly as a primary one does. */
+ const clientTools = createClientToolHandoff({
+ tools: request.tools,
+ agentDefinitions: primaryConfig.toolDefinitions,
+ serverDefinitions: modelBoundAgents.flatMap((runAgent) => runAgent.toolDefinitions ?? []),
+ responseId,
+ });
+ if (clientTools.error != null) {
+ return sendResponsesErrorResponse(res, 400, clientTools.error, 'invalid_request');
+ }
+ primaryConfig.toolDefinitions = clientTools.toolDefinitions;
+ context.tools = clientTools.appliedTools;
+
const toolSet = buildRunToolSet(
primaryConfig,
handoffAgentConfigs.values(),
@@ -1169,6 +1189,9 @@ const executeResponse = async (envelope, { req, res }) => {
res,
context,
tracker,
+ /* The run terminates a caller-executed call's item itself: the server
+ never executes one, so `on_tool_end` cannot. */
+ clientToolNames: clientTools.clientToolNames,
};
// Emit response.created then response.in_progress per Open Responses spec
@@ -1176,8 +1199,11 @@ const executeResponse = async (envelope, { req, res }) => {
emitResponseInProgress(handlerConfig);
// Create event handlers
- const { handlers: responsesHandlers, finalizeStream } =
- createResponsesEventHandlers(handlerConfig);
+ const {
+ handlers: responsesHandlers,
+ finalizeStream,
+ emitClientToolDeferral,
+ } = createResponsesEventHandlers(handlerConfig);
// Collect usage for balance tracking
const collectedUsage = [];
@@ -1245,7 +1271,7 @@ const executeResponse = async (envelope, { req, res }) => {
const handlers = {
on_message_delta: responsesHandlers.on_message_delta,
on_reasoning_delta: responsesHandlers.on_reasoning_delta,
- on_run_step: responsesHandlers.on_run_step,
+ on_run_step: clientTools.wrapRunStep(responsesHandlers.on_run_step),
on_run_step_delta: responsesHandlers.on_run_step_delta,
on_chat_model_end: {
handle: (event, data, metadata, graph) => {
@@ -1264,7 +1290,12 @@ const executeResponse = async (envelope, { req, res }) => {
on_chain_end: { handle: () => {} },
on_agent_update: { handle: () => {} },
on_custom_event: { handle: () => {} },
- on_tool_execute: createToolExecuteHandler(toolExecuteOptions),
+ /** The deferral answer is emitted as the call's `function_call_output`,
+ * so a caller can tell an answered call from one handed back to it. */
+ on_tool_execute: clientTools.wrapToolExecute(
+ createToolExecuteHandler(toolExecuteOptions),
+ emitClientToolDeferral,
+ ),
on_agent_log: agentLogHandlerObj,
...(summarizationConfig?.enabled !== false
? buildSummarizationHandlers({ isStreaming: actuallyStreaming, res })
@@ -1291,6 +1322,7 @@ const executeResponse = async (envelope, { req, res }) => {
traceContext: { endpoint: EModelEndpoint.agents },
tenantId: principal.tenantId,
modelCallbacks: [terminalRunError.modelCallback],
+ clientToolNames: clientTools.clientToolNames,
/** Bills subagent child-run model calls (reported outside the
* streamEvents loop) into the same collectedUsage array. */
subagentUsageSink: createSubagentUsageSink(collectedUsage),
@@ -1475,7 +1507,7 @@ const executeResponse = async (envelope, { req, res }) => {
const handlers = {
on_message_delta: aggregatorHandlers.on_message_delta,
on_reasoning_delta: aggregatorHandlers.on_reasoning_delta,
- on_run_step: aggregatorHandlers.on_run_step,
+ on_run_step: clientTools.wrapRunStep(aggregatorHandlers.on_run_step),
on_run_step_delta: aggregatorHandlers.on_run_step_delta,
on_chat_model_end: {
handle: (event, data, metadata, graph) => {
@@ -1494,7 +1526,10 @@ const executeResponse = async (envelope, { req, res }) => {
on_chain_end: { handle: () => {} },
on_agent_update: { handle: () => {} },
on_custom_event: { handle: () => {} },
- on_tool_execute: createToolExecuteHandler(toolExecuteOptions),
+ on_tool_execute: clientTools.wrapToolExecute(
+ createToolExecuteHandler(toolExecuteOptions),
+ (callId, output) => aggregator.toolOutputs.set(callId, output),
+ ),
on_agent_log: agentLogHandlerObj,
...(summarizationConfig?.enabled !== false
? buildSummarizationHandlers({ isStreaming: false, res })
@@ -1520,6 +1555,7 @@ const executeResponse = async (envelope, { req, res }) => {
traceContext: { endpoint: EModelEndpoint.agents },
tenantId: principal.tenantId,
modelCallbacks: [terminalRunError.modelCallback],
+ clientToolNames: clientTools.clientToolNames,
/** Bills subagent child-run model calls (reported outside the
* streamEvents loop) into the same collectedUsage array. */
subagentUsageSink: createSubagentUsageSink(collectedUsage),
diff --git a/packages/api/src/agents/responses/__tests__/service.test.ts b/packages/api/src/agents/responses/__tests__/service.test.ts
index 3d364e8223..12c3c687a5 100644
--- a/packages/api/src/agents/responses/__tests__/service.test.ts
+++ b/packages/api/src/agents/responses/__tests__/service.test.ts
@@ -1,3 +1,5 @@
+import { formatAgentMessages, Providers } from '@librechat/agents';
+import type { ToolExecuteBatchRequest } from '@librechat/agents';
import type { Response as ServerResponse } from 'express';
import type { InputItem, ResponseContext } from '../types';
import {
@@ -6,9 +8,14 @@ import {
createAggregatorEventHandlers,
createResponseAggregator,
createResponsesEventHandlers,
+ validateResponseRequest,
+ createResponseContext,
buildResponsesUsage,
} from '../service';
-import { createResponseTracker } from '../handlers';
+import { clientToolDeferralContent, createClientToolExecuteHandler } from '../clientTools';
+import { extractMessageContent } from '~/protection/adapters/messages';
+import { buildResponse, createResponseTracker } from '../handlers';
+import { buildRunToolSet } from '~/agents/tools';
describe('response usage aggregation', () => {
const context: ResponseContext = {
@@ -99,6 +106,302 @@ describe('response usage aggregation', () => {
});
});
+/**
+ * A caller-executed tool is never run by the server, so `on_tool_end` — where a
+ * server-run call gets its terminating events — cannot fire for it. The
+ * streaming lifecycle still has to end the item, otherwise the caller that must
+ * run the tool is handed an item that never closes.
+ */
+describe('streaming lifecycle of a caller-executed tool call', () => {
+ const context: ResponseContext = {
+ responseId: 'resp_test',
+ model: 'agent_test',
+ createdAt: 1778317637,
+ };
+ const CALL_ID = 'toolu_stream_1';
+ const CLIENT_TOOL = 'submit_sql';
+
+ /** Collects the events one streamed run writes, as parsed payloads. */
+ function recorder(): { res: ServerResponse; events: Array<Record<string, unknown>> } {
+ const events: Array<Record<string, unknown>> = [];
+ const res = {
+ write: (chunk: string) => {
+ if (chunk.startsWith('data: ') && !chunk.includes('[DONE]')) {
+ events.push(JSON.parse(chunk.slice(6)));
+ }
+ },
+ } as unknown as ServerResponse;
+ return { res, events };
+ }
+
+ /** The terminating events for the call itself; the tool result is its own
+ * `function_call_output` item and closes separately. */
+ function terminatingEvents(events: Array<Record<string, unknown>>): string[] {
+ return events
+ .filter(
+ (event) =>
+ event.type === 'response.function_call_arguments.done' ||
+ (event.type === 'response.output_item.done' &&
+ (event.item as { type?: string } | undefined)?.type === 'function_call'),
+ )
+ .map((event) => event.type as string);
+ }
+
+ /** Streams one call to `toolName`, then ends the run as the graph would. */
+ function streamToolCall(toolName: string): Array<Record<string, unknown>> {
+ const { res, events } = recorder();
+ const { handlers, finalizeStream } = createResponsesEventHandlers({
+ res,
+ context,
+ tracker: createResponseTracker(),
+ clientToolNames: new Set([CLIENT_TOOL]),
+ });
+
+ handlers.on_run_step.handle('on_run_step', {
+ id: 'step_1',
+ stepDetails: { type: 'tool_calls', tool_calls: [{ id: CALL_ID, name: toolName }] },
+ });
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_1',
+ delta: { type: 'tool_calls', tool_calls: [{ id: CALL_ID, index: 0, args: '{"sql":' }] },
+ });
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_1',
+ delta: { type: 'tool_calls', tool_calls: [{ index: 0, args: '"SELECT 1"}' }] },
+ });
+ finalizeStream();
+
+ return events;
+ }
+
+ const streamClientToolCall = (): Array<Record<string, unknown>> => streamToolCall(CLIENT_TOOL);
+
+ it('terminates the arguments and the item before the response completes', () => {
+ const types = streamClientToolCall().map((event) => event.type);
+
+ expect(types).toEqual([
+ 'response.output_item.added',
+ 'response.function_call_arguments.delta',
+ 'response.function_call_arguments.delta',
+ 'response.function_call_arguments.done',
+ 'response.output_item.done',
+ 'response.completed',
+ ]);
+ });
+
+ it('reports the assembled arguments on the terminating events', () => {
+ const events = streamClientToolCall();
+ const argumentsDone = events.find(
+ (event) => event.type === 'response.function_call_arguments.done',
+ );
+
+ expect(argumentsDone).toMatchObject({
+ call_id: CALL_ID,
+ arguments: '{"sql":"SELECT 1"}',
+ });
+ });
+
+ it('leaves no item in progress inside a completed response', () => {
+ const events = streamClientToolCall();
+ const completed = events.find((event) => event.type === 'response.completed') as {
+ response: { status: string; output: Array<{ type: string; status?: string }> };
+ };
+
+ expect(completed.response.status).toBe('completed');
+ expect(completed.response.output).toEqual([
+ expect.objectContaining({ type: 'function_call', status: 'completed' }),
+ ]);
+ });
+
+ /**
+ * The first tool call of a message is announced before its arguments arrive,
+ * but a second one is announced after them: the SDK opens a single
+ * `tool_calls` run step per message, so any later call gets its own step only
+ * at model end.
+ *
+ * An argument fragment that arrives before its call is announced has no item
+ * to write to, so it is dropped. `on_chat_model_end` is what puts those
+ * arguments back, and the only way it can tell they were dropped is by
+ * checking what the tracker actually holds.
+ */
+ it('recovers the arguments of a call announced after its own fragments', () => {
+ const { res, events } = recorder();
+ const { handlers, finalizeStream } = createResponsesEventHandlers({
+ res,
+ context,
+ tracker: createResponseTracker(),
+ clientToolNames: new Set([CLIENT_TOOL]),
+ });
+ const FIRST = 'toolu_first';
+ const SECOND = 'toolu_second';
+
+ handlers.on_run_step.handle('on_run_step', {
+ id: 'step_1',
+ stepDetails: { type: 'tool_calls', tool_calls: [{ id: FIRST, name: CLIENT_TOOL }] },
+ });
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_1',
+ delta: { type: 'tool_calls', tool_calls: [{ id: FIRST, index: 1, args: '{"sql":"A"}' }] },
+ });
+ /* The second block opens with the id, and its fragments follow, all before
+ the run step that announces it. */
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_1',
+ delta: {
+ type: 'tool_calls',
+ tool_calls: [{ id: SECOND, name: CLIENT_TOOL, index: 2, args: '' }],
+ },
+ });
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_1',
+ delta: { type: 'tool_calls', tool_calls: [{ index: 2, args: '{"sql":"B"}' }] },
+ });
+ handlers.on_run_step.handle('on_run_step', {
+ id: 'step_2',
+ stepDetails: { type: 'tool_calls', tool_calls: [{ id: SECOND, name: CLIENT_TOOL }] },
+ });
+ handlers.on_chat_model_end.handle('on_chat_model_end', {
+ output: {
+ tool_calls: [
+ { id: FIRST, args: { sql: 'A' } },
+ { id: SECOND, args: { sql: 'B' } },
+ ],
+ },
+ });
+ finalizeStream();
+
+ const completed = events.find((event) => event.type === 'response.completed') as {
+ response: { output: Array<{ call_id?: string; arguments?: string }> };
+ };
+
+ expect(completed.response.output).toEqual([
+ expect.objectContaining({ call_id: FIRST, arguments: '{"sql":"A"}' }),
+ expect.objectContaining({ call_id: SECOND, arguments: '{"sql":"B"}' }),
+ ]);
+ });
+
+ /** The first call's fragments are already streamed, so the backfill must not
+ * append the model-end copy on top of them. */
+ it('does not duplicate arguments a call already streamed', () => {
+ const { res, events } = recorder();
+ const { handlers, finalizeStream } = createResponsesEventHandlers({
+ res,
+ context,
+ tracker: createResponseTracker(),
+ clientToolNames: new Set([CLIENT_TOOL]),
+ });
+
+ handlers.on_run_step.handle('on_run_step', {
+ id: 'step_1',
+ stepDetails: { type: 'tool_calls', tool_calls: [{ id: CALL_ID, name: CLIENT_TOOL }] },
+ });
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_1',
+ delta: { type: 'tool_calls', tool_calls: [{ id: CALL_ID, index: 0, args: '{"sql":' }] },
+ });
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_1',
+ delta: { type: 'tool_calls', tool_calls: [{ index: 0, args: '"SELECT 1"}' }] },
+ });
+ handlers.on_chat_model_end.handle('on_chat_model_end', {
+ output: { tool_calls: [{ id: CALL_ID, args: { sql: 'SELECT 1' } }] },
+ });
+ finalizeStream();
+
+ const argumentsDone = events.find(
+ (event) => event.type === 'response.function_call_arguments.done',
+ );
+
+ expect(argumentsDone).toMatchObject({
+ call_id: CALL_ID,
+ arguments: '{"sql":"SELECT 1"}',
+ });
+ });
+
+ /**
+ * A call the server answered itself must not look like one handed back for
+ * the caller to run: the model was told to re-issue it, so a caller that
+ * executed it too would run a side-effecting tool twice.
+ */
+ it('reports a deferred call as answered, not as handed back', () => {
+ const { res, events } = recorder();
+ const { handlers, finalizeStream, emitClientToolDeferral } = createResponsesEventHandlers({
+ res,
+ context,
+ tracker: createResponseTracker(),
+ clientToolNames: new Set([CLIENT_TOOL]),
+ });
+ const execute = createClientToolExecuteHandler({
+ delegate: { handle: () => {} },
+ clientToolNames: new Set([CLIENT_TOOL]),
+ responseId: 'resp_test',
+ onDeferred: emitClientToolDeferral,
+ });
+
+ handlers.on_run_step.handle('on_run_step', {
+ id: 'step_1',
+ stepDetails: { type: 'tool_calls', tool_calls: [{ id: CALL_ID, name: CLIENT_TOOL }] },
+ });
+ execute.handle('on_tool_execute', {
+ toolCalls: [{ id: CALL_ID, name: CLIENT_TOOL, args: {} }],
+ resolve: () => {},
+ } as unknown as ToolExecuteBatchRequest);
+ finalizeStream();
+
+ const completed = events.find((event) => event.type === 'response.completed') as {
+ response: { output: Array<{ type: string; call_id?: string; output?: string }> };
+ };
+ const answer = completed.response.output.find((item) => item.type === 'function_call_output');
+
+ expect(answer).toMatchObject({
+ call_id: CALL_ID,
+ output: clientToolDeferralContent(CLIENT_TOOL),
+ });
+ });
+
+ /**
+ * A mixed batch answers the client call server-side, which can terminate it
+ * through `on_tool_end` after all. Finalization must not emit a second pair
+ * for a call that already closed.
+ */
+ it('does not re-terminate a call on_tool_end already closed', () => {
+ const { res, events } = recorder();
+ const { handlers, finalizeStream } = createResponsesEventHandlers({
+ res,
+ context,
+ tracker: createResponseTracker(),
+ clientToolNames: new Set([CLIENT_TOOL]),
+ });
+
+ handlers.on_run_step.handle('on_run_step', {
+ id: 'step_1',
+ stepDetails: { type: 'tool_calls', tool_calls: [{ id: CALL_ID, name: CLIENT_TOOL }] },
+ });
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_1',
+ delta: { type: 'tool_calls', tool_calls: [{ id: CALL_ID, index: 0, args: '{}' }] },
+ });
+ handlers.on_tool_end.handle('on_tool_end', { tool_call_id: CALL_ID, output: 'done' });
+ finalizeStream();
+
+ expect(terminatingEvents(events)).toEqual([
+ 'response.function_call_arguments.done',
+ 'response.output_item.done',
+ ]);
+ });
+
+ /**
+ * Scoping, pinned: a server tool's call is `on_tool_end`'s to terminate, and
+ * this module never sees that event because the controller replaces the
+ * handler instead of composing with it. Terminating such a call from
+ * finalization would paper over that separate bug AND change the event stream
+ * of every request that declares no client tool, so it deliberately does not.
+ */
+ it('leaves a server tool call to on_tool_end', () => {
+ expect(terminatingEvents(streamToolCall('bash_tool'))).toEqual([]);
+ });
+});
+
describe('convertInputToMessages', () => {
// ── String input shorthand ─────────────────────────────────────────
it('converts a string input to a single user message', () => {
@@ -341,7 +644,7 @@ describe('convertInputToMessages', () => {
});
// ── Function call items ────────────────────────────────────────────
- it('converts function_call items to assistant messages with tool_calls', () => {
+ it('pairs a function_call with its output into one assistant tool_call part', () => {
const input: InputItem[] = [
{
type: 'function_call',
@@ -350,42 +653,70 @@ describe('convertInputToMessages', () => {
name: 'get_weather',
arguments: '{"city":"NYC"}',
},
+ { type: 'function_call_output', call_id: 'call_abc', output: '{"temp":72}' },
];
const result = convertInputToMessages(input);
expect(result).toEqual([
{
role: 'assistant',
- content: '',
- tool_calls: [
+ content: [
{
- id: 'call_abc',
- type: 'function',
- function: { name: 'get_weather', arguments: '{"city":"NYC"}' },
+ type: 'tool_call',
+ tool_call: {
+ id: 'call_abc',
+ name: 'get_weather',
+ args: '{"city":"NYC"}',
+ output: '{"temp":72}',
+ },
},
],
},
]);
});
- // ── Function call output items ─────────────────────────────────────
- it('converts function_call_output items to tool messages', () => {
+ it('never emits a tool-role message, which formats as a stray SystemMessage', () => {
const input: InputItem[] = [
+ { type: 'message', role: 'user', content: 'Run it' },
{
- type: 'function_call_output',
+ type: 'function_call',
+ id: 'fc_1',
call_id: 'call_abc',
- output: '{"temp":72}',
+ name: 'get_weather',
+ arguments: '{}',
},
+ { type: 'function_call_output', call_id: 'call_abc', output: 'ok' },
];
const result = convertInputToMessages(input);
- expect(result).toEqual([
- {
- role: 'tool',
- content: '{"temp":72}',
- tool_call_id: 'call_abc',
- },
+ expect(result.map((message) => message.role)).toEqual(['user', 'assistant']);
+ });
+
+ it('keeps a parallel batch on a single assistant turn', () => {
+ const input: InputItem[] = [
+ { type: 'function_call', id: 'fc_1', call_id: 'call_a', name: 'first', arguments: '{}' },
+ { type: 'function_call', id: 'fc_2', call_id: 'call_b', name: 'second', arguments: '{}' },
+ { type: 'function_call_output', call_id: 'call_a', output: 'a' },
+ { type: 'function_call_output', call_id: 'call_b', output: 'b' },
+ ];
+ const result = convertInputToMessages(input);
+ expect(result).toHaveLength(1);
+ expect(result[0].content).toEqual([
+ { type: 'tool_call', tool_call: { id: 'call_a', name: 'first', args: '{}', output: 'a' } },
+ { type: 'tool_call', tool_call: { id: 'call_b', name: 'second', args: '{}', output: 'b' } },
]);
});
+ it('starts a new assistant turn when a message separates two calls', () => {
+ const input: InputItem[] = [
+ { type: 'function_call', id: 'fc_1', call_id: 'call_a', name: 'first', arguments: '{}' },
+ { type: 'function_call_output', call_id: 'call_a', output: 'a' },
+ { type: 'message', role: 'user', content: 'And again' },
+ { type: 'function_call', id: 'fc_2', call_id: 'call_b', name: 'second', arguments: '{}' },
+ { type: 'function_call_output', call_id: 'call_b', output: 'b' },
+ ];
+ const result = convertInputToMessages(input);
+ expect(result.map((message) => message.role)).toEqual(['assistant', 'user', 'assistant']);
+ });
+
// ── Item references are skipped ────────────────────────────────────
it('skips item_reference items', () => {
const input: InputItem[] = [
@@ -429,3 +760,469 @@ describe('convertInputToMessages', () => {
]);
});
});
+
+describe('tool call argument attribution', () => {
+ /** Reproduces the SQL Console construct run: an MCP lookup, then a caller-declared submit_sql. */
+ it('keeps arguments with their own call when a run makes two calls in separate steps', () => {
+ const aggregator = createResponseAggregator();
+ const handlers = createAggregatorEventHandlers(aggregator);
+
+ handlers.on_run_step.handle('on_run_step', {
+ id: 'step_1',
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'toolu_lookup', name: 'list_tables' }],
+ },
+ });
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_1',
+ delta: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'toolu_lookup', index: 1, args: '{"database":' }],
+ },
+ });
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_1',
+ delta: { type: 'tool_calls', tool_calls: [{ index: 1, args: '"default"}' }] },
+ });
+
+ handlers.on_run_step.handle('on_run_step', {
+ id: 'step_2',
+ stepDetails: { type: 'tool_calls', tool_calls: [{ id: 'toolu_submit', name: 'submit_sql' }] },
+ });
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_2',
+ delta: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'toolu_submit', index: 1, args: '{"sql":' }],
+ },
+ });
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_2',
+ delta: { type: 'tool_calls', tool_calls: [{ index: 1, args: '"SELECT 1"}' }] },
+ });
+
+ expect(aggregator.toolCalls.get('toolu_lookup')?.arguments).toBe('{"database":"default"}');
+ expect(aggregator.toolCalls.get('toolu_submit')?.arguments).toBe('{"sql":"SELECT 1"}');
+ });
+
+ it('separates two calls made in one step under provider content-block indexes', () => {
+ const aggregator = createResponseAggregator();
+ const handlers = createAggregatorEventHandlers(aggregator);
+
+ handlers.on_run_step.handle('on_run_step', {
+ id: 'step_1',
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [
+ { id: 'toolu_a', name: 'list_tables' },
+ { id: 'toolu_b', name: 'submit_sql' },
+ ],
+ },
+ });
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_1',
+ delta: {
+ type: 'tool_calls',
+ tool_calls: [
+ { id: 'toolu_a', index: 1, args: '{"a":1}' },
+ { id: 'toolu_b', index: 2, args: '{"sql":' },
+ ],
+ },
+ });
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_1',
+ delta: { type: 'tool_calls', tool_calls: [{ index: 2, args: '"SELECT 2"}' }] },
+ });
+
+ expect(aggregator.toolCalls.get('toolu_a')?.arguments).toBe('{"a":1}');
+ expect(aggregator.toolCalls.get('toolu_b')?.arguments).toBe('{"sql":"SELECT 2"}');
+ });
+
+ it('attributes an index-less chunk to the only call in the step', () => {
+ const aggregator = createResponseAggregator();
+ const handlers = createAggregatorEventHandlers(aggregator);
+
+ handlers.on_run_step.handle('on_run_step', {
+ id: 'step_1',
+ stepDetails: { type: 'tool_calls', tool_calls: [{ id: 'toolu_only', name: 'submit_sql' }] },
+ });
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_1',
+ delta: { type: 'tool_calls', tool_calls: [{ args: '{"sql":"SELECT 3"}' }] },
+ });
+
+ expect(aggregator.toolCalls.get('toolu_only')?.arguments).toBe('{"sql":"SELECT 3"}');
+ });
+
+ it('drops an unattributable chunk rather than guessing between two calls', () => {
+ const aggregator = createResponseAggregator();
+ const handlers = createAggregatorEventHandlers(aggregator);
+
+ handlers.on_run_step.handle('on_run_step', {
+ id: 'step_1',
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [
+ { id: 'toolu_a', name: 'list_tables' },
+ { id: 'toolu_b', name: 'submit_sql' },
+ ],
+ },
+ });
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_1',
+ delta: { type: 'tool_calls', tool_calls: [{ index: 7, args: '{"sql":"nope"}' }] },
+ });
+
+ expect(aggregator.toolCalls.get('toolu_a')?.arguments).toBe('');
+ expect(aggregator.toolCalls.get('toolu_b')?.arguments).toBe('');
+ });
+
+ it('seeds arguments a provider delivers on the step instead of as deltas', () => {
+ const aggregator = createResponseAggregator();
+ const handlers = createAggregatorEventHandlers(aggregator);
+
+ handlers.on_run_step.handle('on_run_step', {
+ id: 'step_1',
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'toolu_whole', name: 'submit_sql', args: '{"sql":"SELECT 4"}' }],
+ },
+ });
+
+ expect(aggregator.toolCalls.get('toolu_whole')?.arguments).toBe('{"sql":"SELECT 4"}');
+ });
+
+ it('ignores a non-string args object rather than stringifying it', () => {
+ const aggregator = createResponseAggregator();
+ const handlers = createAggregatorEventHandlers(aggregator);
+
+ handlers.on_run_step.handle('on_run_step', {
+ id: 'step_1',
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'toolu_obj', name: 'submit_sql', args: {} }],
+ },
+ });
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_1',
+ delta: { type: 'tool_calls', tool_calls: [{ id: 'toolu_obj', args: { sql: 'SELECT 5' } }] },
+ });
+
+ expect(aggregator.toolCalls.get('toolu_obj')?.arguments).toBe('');
+ });
+});
+
+describe('tool call arguments from the completed model message', () => {
+ const SQL = 'SELECT\n created_at\nFROM default.analytics_test_v2\nLIMIT 100';
+
+ /**
+ * The SQL Console construct run: the provider sent list_tables as fragments and submit_sql
+ * whole, so only the completed message carries the query.
+ */
+ it('fills arguments for a call the provider delivered without fragments', () => {
+ const aggregator = createResponseAggregator();
+ const handlers = createAggregatorEventHandlers(aggregator);
+
+ handlers.on_run_step.handle('on_run_step', {
+ id: 'step_1',
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'toolu_lookup', name: 'list_tables' }],
+ },
+ });
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_1',
+ delta: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'toolu_lookup', index: 1, args: '{"database":"default"}' }],
+ },
+ });
+ handlers.on_chat_model_end.handle('on_chat_model_end', {
+ output: {
+ tool_calls: [{ id: 'toolu_lookup', args: { database: 'default' } }],
+ },
+ });
+
+ handlers.on_run_step.handle('on_run_step', {
+ id: 'step_2',
+ stepDetails: { type: 'tool_calls', tool_calls: [{ id: 'toolu_submit', name: 'submit_sql' }] },
+ });
+ handlers.on_chat_model_end.handle('on_chat_model_end', {
+ output: { tool_calls: [{ id: 'toolu_submit', args: { sql: SQL } }] },
+ });
+
+ expect(aggregator.toolCalls.get('toolu_lookup')?.arguments).toBe('{"database":"default"}');
+ expect(JSON.parse(aggregator.toolCalls.get('toolu_submit')?.arguments ?? '{}')).toEqual({
+ sql: SQL,
+ });
+ });
+
+ it('leaves fragment-accumulated arguments untouched', () => {
+ const aggregator = createResponseAggregator();
+ const handlers = createAggregatorEventHandlers(aggregator);
+
+ handlers.on_run_step.handle('on_run_step', {
+ id: 'step_1',
+ stepDetails: { type: 'tool_calls', tool_calls: [{ id: 'toolu_a', name: 'submit_sql' }] },
+ });
+ handlers.on_run_step_delta.handle('on_run_step_delta', {
+ id: 'step_1',
+ delta: { type: 'tool_calls', tool_calls: [{ id: 'toolu_a', args: '{"sql":"SELECT 1"}' }] },
+ });
+ handlers.on_chat_model_end.handle('on_chat_model_end', {
+ output: { tool_calls: [{ id: 'toolu_a', args: { sql: 'SELECT 999' } }] },
+ });
+
+ expect(aggregator.toolCalls.get('toolu_a')?.arguments).toBe('{"sql":"SELECT 1"}');
+ });
+
+ it('ignores completed calls the run never announced, and usage still accumulates', () => {
+ const aggregator = createResponseAggregator();
+ const handlers = createAggregatorEventHandlers(aggregator);
+
+ handlers.on_chat_model_end.handle('on_chat_model_end', {
+ output: {
+ usage_metadata: { input_tokens: 10, output_tokens: 2 },
+ tool_calls: [{ id: 'toolu_unknown', args: { sql: 'SELECT 1' } }],
+ },
+ });
+
+ expect(aggregator.toolCalls.size).toBe(0);
+ expect(aggregator.usage.inputTokens).toBe(10);
+ });
+});
+
+/**
+ * The continuation a caller-executed tool needs. `previous_response_id` cannot
+ * carry a tool exchange — a turn is persisted as text, so neither item of the
+ * pair survives it — which leaves replaying both items in `input` as the only
+ * supported shape. See the `clientTools` module docstring.
+ */
+describe('client tool continuation replay', () => {
+ const CALL_ID = 'call_submit_1';
+ const TOOL_NAME = 'submit_sql';
+
+ const replayInput: InputItem[] = [
+ { type: 'message', role: 'user', content: 'Run the query' },
+ {
+ type: 'function_call',
+ id: 'fc_1',
+ call_id: CALL_ID,
+ name: TOOL_NAME,
+ arguments: '{"sql":"SELECT 1"}',
+ },
+ { type: 'function_call_output', call_id: CALL_ID, output: 'submitted' },
+ ];
+
+ it('pairs a replayed function_call with its output on one assistant turn', () => {
+ expect(convertInputToMessages(replayInput)).toEqual([
+ { role: 'user', content: 'Run the query' },
+ {
+ role: 'assistant',
+ content: [
+ {
+ type: 'tool_call',
+ tool_call: {
+ id: CALL_ID,
+ name: TOOL_NAME,
+ args: '{"sql":"SELECT 1"}',
+ output: 'submitted',
+ },
+ },
+ ],
+ },
+ ]);
+ });
+
+ /**
+ * The conversion is only half the contract: the controller hands these
+ * messages to `formatAgentMessages`, which reads a tool exchange ONLY from a
+ * `tool_call` content part. Asserting the converted shape in isolation is
+ * what let the earlier OpenAI-style `{ role: 'tool' }` message pass its unit
+ * test and still fail every live replay — `formatMessage` has no branch for
+ * that role, so it became a SystemMessage mid-conversation and Anthropic
+ * rejected the payload ("System messages are only permitted as the first
+ * passed message"). This test formats what the controller formats.
+ */
+ it('formats the replay into a paired tool_use and tool result', () => {
+ const toolSet = buildRunToolSet({
+ toolDefinitions: [{ name: TOOL_NAME, description: 'caller-executed', schema: {} }],
+ } as never);
+ expect(toolSet.has(TOOL_NAME)).toBe(true);
+
+ const { messages } = formatAgentMessages(
+ convertInputToMessages(replayInput) as never,
+ {},
+ toolSet,
+ undefined,
+ { provider: Providers.ANTHROPIC },
+ );
+
+ /** The invariant `_convertMessagesToAnthropicPayload` enforces before it
+ * throws: nothing past the first message may be a system message. */
+ expect(messages.slice(1).map((message) => message._getType())).not.toContain('system');
+ expect(messages.map((message) => message._getType())).toEqual(['human', 'ai', 'tool']);
+
+ /** The call rides on the AIMessage as a parsed `tool_calls` entry — the
+ * provider integration renders it as the tool-use block. */
+ const toolCalls = (messages[1] as unknown as { tool_calls?: Array<Record<string, unknown>> })
+ .tool_calls;
+ expect(toolCalls).toEqual([{ id: CALL_ID, name: TOOL_NAME, args: { sql: 'SELECT 1' } }]);
+
+ const toolResult = messages[2] as unknown as { tool_call_id: string; content: unknown };
+ expect(toolResult.tool_call_id).toBe(CALL_ID);
+ expect(toolResult.content).toBe('submitted');
+ });
+
+ /**
+ * The replayed arguments and result moved out of a message's own `content`
+ * and into a `tool_call` part, and the controller runs the content filter
+ * over these same messages (`extractMessageContent`) before the run starts.
+ * Caller-supplied text must stay reachable by that traversal: a shape the
+ * filter cannot see is a filter that silently stops covering the replay.
+ */
+ it('keeps replayed tool text visible to the content-filter traversal', () => {
+ const fragments = [...extractMessageContent(convertInputToMessages(replayInput) as never)].map(
+ (fragment) => fragment.text,
+ );
+
+ expect(fragments).toContain('{"sql":"SELECT 1"}');
+ expect(fragments).toContain('submitted');
+ });
+
+ /**
+ * What a caller gets wrong by following the OpenAI habit of sending only the
+ * output: the tool result arrives with no call to answer. Rejected at ingress
+ * with a message that names the item, rather than reaching the provider and
+ * coming back as an opaque upstream failure.
+ */
+ it('rejects a bare function_call_output', () => {
+ const result = validateResponseRequest({
+ model: 'agent_test',
+ input: [{ type: 'function_call_output', call_id: CALL_ID, output: 'submitted' }],
+ });
+
+ expect(result.valid).toBe(false);
+ expect((result as { error: string }).error).toContain(
+ `function_call_output ${CALL_ID} has no matching function_call`,
+ );
+ });
+
+ /** Only the caller can answer a call to its own tool, so only there is the
+ * missing half the caller's mistake. */
+ it('rejects a function_call to a declared tool whose output was not replayed', () => {
+ const result = validateResponseRequest({
+ model: 'agent_test',
+ input: replayInput.slice(0, 2),
+ tools: [{ type: 'function', name: TOOL_NAME, parameters: { type: 'object' } }],
+ });
+
+ expect(result.valid).toBe(false);
+ expect((result as { error: string }).error).toContain(
+ `function_call ${CALL_ID} has no function_call_output`,
+ );
+ });
+
+ /**
+ * The server emits a `function_call` for its own tools but never a
+ * `function_call_output`, so appending a previous response's `output` to the
+ * next request's `input` — the usual continuation — carries calls the caller
+ * cannot answer. Refusing those would reject a transcript the server itself
+ * produced.
+ */
+ it('accepts an unanswered call to a tool the caller did not declare', () => {
+ const result = validateResponseRequest({
+ model: 'agent_test',
+ input: replayInput.slice(0, 2),
+ });
+
+ expect(result.valid).toBe(true);
+ });
+
+ it('drops an unanswered server call rather than replaying it with no result', () => {
+ const messages = convertInputToMessages(replayInput.slice(0, 2));
+
+ expect(messages).toEqual([{ role: 'user', content: 'Run the query' }]);
+ });
+
+ it.each([
+ ['a duplicate call_id', [replayInput[1], replayInput[1]], 'duplicate function_call call_id'],
+ [
+ 'non-string arguments',
+ [{ type: 'function_call', id: 'fc_1', call_id: CALL_ID, name: TOOL_NAME, arguments: {} }],
+ 'requires arguments as a JSON string',
+ ],
+ [
+ 'a missing call_id',
+ [{ type: 'function_call', id: 'fc_1', name: TOOL_NAME, arguments: '{}' }],
+ 'requires a non-empty string call_id',
+ ],
+ ])('rejects %s', (_label, input, expected) => {
+ const result = validateResponseRequest({ model: 'agent_test', input });
+
+ expect(result.valid).toBe(false);
+ expect((result as { error: string }).error).toContain(expected as string);
+ });
+});
+
+describe('reported tools and tool_choice', () => {
+ const context: ResponseContext = {
+ responseId: 'resp_test',
+ model: 'agent_test',
+ createdAt: 1778317637,
+ };
+
+ /**
+ * `tool_choice` is never forwarded to the model, so echoing the request's ask
+ * would tell the caller a directive was applied when the run ignored it.
+ */
+ it.each([
+ ['required', 'required'],
+ ['none', 'none'],
+ ['a specific function', { type: 'function', name: 'submit_sql' }],
+ ])('reports tool_choice as auto when the request asked for %s', (_label, toolChoice) => {
+ const { request } = validateResponseRequest({
+ model: 'agent_test',
+ input: 'hi',
+ tool_choice: toolChoice,
+ });
+ const built = createResponseContext(request!, 'resp_test');
+
+ expect(built).not.toHaveProperty('toolChoice');
+ expect(buildAggregatedResponse(built, createResponseAggregator()).tool_choice).toBe('auto');
+ expect(buildResponse(built, createResponseTracker(), 'completed').tool_choice).toBe('auto');
+ });
+
+ it('does not report a request tool until the run resolves which ones applied', () => {
+ const { request } = validateResponseRequest({
+ model: 'agent_test',
+ input: 'hi',
+ tools: [{ type: 'function', name: 'submit_sql' }],
+ });
+ const built = createResponseContext(request!, 'resp_test');
+
+ expect(built.tools).toBeUndefined();
+ expect(buildAggregatedResponse(built, createResponseAggregator()).tools).toEqual([]);
+ });
+
+ it('reports the applied tools the run recorded on the context', () => {
+ const applied: ResponseContext = {
+ ...context,
+ tools: [{ type: 'function', name: 'submit_sql' }],
+ };
+
+ expect(buildAggregatedResponse(applied, createResponseAggregator()).tools).toEqual([
+ { type: 'function', name: 'submit_sql' },
+ ]);
+ expect(buildResponse(applied, createResponseTracker(), 'completed').tools).toEqual([
+ { type: 'function', name: 'submit_sql' },
+ ]);
+ });
+
+ it('rejects a malformed tools entry at ingress', () => {
+ expect(
+ validateResponseRequest({ model: 'agent_test', input: 'hi', tools: ['submit_sql'] }),
+ ).toEqual({ valid: false, error: expect.stringContaining('tools[0] must be an object') });
+ });
+});
diff --git a/packages/api/src/agents/responses/clientTools.sdk.spec.ts b/packages/api/src/agents/responses/clientTools.sdk.spec.ts
new file mode 100644
index 0000000000..7d54182503
--- /dev/null
+++ b/packages/api/src/agents/responses/clientTools.sdk.spec.ts
@@ -0,0 +1,263 @@
+import {
+ ChatModelStreamHandler,
+ HandlerRegistry,
+ Providers,
+ StandardGraph,
+ handleToolCalls,
+ toolsCondition,
+} from '@librechat/agents';
+import type { ToolExecuteBatchRequest } from '@librechat/agents';
+import type { Response as ServerResponse } from 'express';
+import { AIMessageChunk } from '@langchain/core/messages';
+import { createClientToolHandoff } from './clientTools';
+import { createResponseTracker } from './handlers';
+import { createResponsesEventHandlers } from './service';
+
+jest.mock('@librechat/data-schemas', () => ({ logger: { warn: jest.fn() } }));
+jest.mock('../usage', () => ({ aggregateCollectedUsage: jest.fn() }));
+
+/** Exercise the SDK's actual step dispatch and stream-key behavior, not stand-in steps. */
+function setup() {
+ const events: Array<{
+ type: string;
+ call_id?: string;
+ arguments?: string;
+ delta?: string;
+ response?: {
+ output: Array<{
+ type: string;
+ call_id?: string;
+ arguments?: string;
+ output?: string;
+ }>;
+ };
+ }> = [];
+ const tracker = createResponseTracker();
+ const handoff = createClientToolHandoff({
+ tools: [{ type: 'function', name: 'submit_sql' }],
+ responseId: 'resp_sdk',
+ });
+ const res = {
+ write: (chunk: string) => {
+ if (chunk.startsWith('data: ') && !chunk.includes('[DONE]')) {
+ events.push(JSON.parse(chunk.slice(6)));
+ }
+ },
+ } as ServerResponse;
+ const stream = createResponsesEventHandlers({
+ res,
+ tracker,
+ context: { responseId: 'resp_sdk', model: 'agent_sdk', createdAt: 0 },
+ clientToolNames: handoff.clientToolNames,
+ });
+ const graph = new StandardGraph({
+ runId: 'sdk',
+ agents: [
+ {
+ agentId: 'agent_sdk',
+ provider: Providers.OPENAI,
+ toolDefinitions: handoff.toolDefinitions,
+ },
+ ],
+ });
+ graph.config = { configurable: { run_id: 'sdk', thread_id: 'sdk_thread' } };
+ const registry = new HandlerRegistry();
+ graph.handlerRegistry = registry;
+ registry.register('on_run_step', handoff.wrapRunStep(stream.handlers.on_run_step));
+ registry.register('on_run_step_delta', stream.handlers.on_run_step_delta);
+ const metadata = {
+ run_id: 'sdk',
+ thread_id: 'sdk_thread',
+ langgraph_node: 'agent=agent_sdk',
+ langgraph_step: 1,
+ };
+ return { events, tracker, handoff, stream, graph, metadata };
+}
+
+const completed = (events: ReturnType<typeof setup>['events']) =>
+ events.find((event) => event.type === 'response.completed')?.response?.output ?? [];
+
+describe('caller tool handoff through the pinned SDK', () => {
+ it('backfills every whole-call argument before closing a parallel batch', async () => {
+ const { events, graph, metadata, stream } = setup();
+ const calls = [
+ { id: 'call_a', name: 'submit_sql', args: { sql: 'SELECT 1' } },
+ { id: 'call_b', name: 'submit_sql', args: { sql: 'SELECT 2' } },
+ ];
+
+ await handleToolCalls(calls, metadata, graph);
+ stream.handlers.on_chat_model_end.handle('on_chat_model_end', {
+ output: { tool_calls: calls },
+ });
+ stream.finalizeStream();
+
+ const done = events.filter((event) => event.type === 'response.function_call_arguments.done');
+ expect(done.map((event) => [event.call_id, event.arguments])).toEqual([
+ ['call_a', '{"sql":"SELECT 1"}'],
+ ['call_b', '{"sql":"SELECT 2"}'],
+ ]);
+ });
+
+ it('emits a deferral result for a client-first mixed batch instead of handing it off', async () => {
+ const { events, handoff, graph, metadata, stream } = setup();
+ const calls = [
+ { id: 'call_a', name: 'submit_sql', args: { sql: 'UPDATE accounts SET x=1' } },
+ { id: 'call_b', name: 'list_tables', args: {} },
+ ];
+ const execute = handoff.wrapToolExecute(
+ {
+ handle: (_event, data) => data.resolve([]),
+ },
+ stream.emitClientToolDeferral,
+ );
+
+ await handleToolCalls(calls, metadata, graph);
+ stream.handlers.on_chat_model_end.handle('on_chat_model_end', {
+ output: { tool_calls: calls },
+ });
+ await execute.handle('on_tool_execute', {
+ toolCalls: calls,
+ resolve: () => {},
+ reject: () => {},
+ } satisfies ToolExecuteBatchRequest);
+ stream.finalizeStream();
+
+ expect(completed(events)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ type: 'function_call_output', call_id: 'call_a' }),
+ ]),
+ );
+ expect(
+ events.filter(
+ (event) =>
+ event.type === 'response.function_call_arguments.done' && event.call_id === 'call_a',
+ ),
+ ).toHaveLength(1);
+ });
+
+ it('waits for whole-call arguments when tool execution beats model end', async () => {
+ const { events, handoff, graph, metadata, stream } = setup();
+ const calls = [
+ { id: 'call_a', name: 'submit_sql', args: { sql: 'UPDATE accounts SET x=1' } },
+ { id: 'call_b', name: 'list_tables', args: {} },
+ ];
+ const execute = handoff.wrapToolExecute(
+ {
+ handle: (_event, data) => data.resolve([]),
+ },
+ stream.emitClientToolDeferral,
+ );
+
+ await handleToolCalls(calls, metadata, graph);
+ await execute.handle('on_tool_execute', {
+ toolCalls: calls,
+ resolve: () => {},
+ reject: () => {},
+ } satisfies ToolExecuteBatchRequest);
+ expect(
+ events.filter((event) => event.type === 'response.function_call_arguments.done'),
+ ).toHaveLength(0);
+ stream.handlers.on_chat_model_end.handle('on_chat_model_end', {
+ output: { tool_calls: calls },
+ });
+ stream.finalizeStream();
+
+ expect(
+ events.find((event) => event.type === 'response.function_call_arguments.done'),
+ ).toMatchObject({
+ call_id: 'call_a',
+ arguments: '{"sql":"UPDATE accounts SET x=1"}',
+ });
+ expect(completed(events)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ type: 'function_call_output', call_id: 'call_a' }),
+ ]),
+ );
+ });
+
+ it('recovers only the missing suffix when a handoff mark moves an index-only chunk', async () => {
+ const { events, graph, metadata, stream } = setup();
+ const sdk = new ChatModelStreamHandler();
+ await sdk.handle(
+ 'on_chat_model_stream',
+ {
+ chunk: new AIMessageChunk({
+ content: '',
+ tool_call_chunks: [{ id: 'call_a', name: 'submit_sql', index: 0, args: '{"sql":' }],
+ }),
+ },
+ metadata,
+ graph,
+ );
+ await sdk.handle(
+ 'on_chat_model_stream',
+ {
+ chunk: new AIMessageChunk({
+ content: '',
+ tool_call_chunks: [{ index: 0, args: '"SELECT 1"}' }],
+ }),
+ },
+ metadata,
+ graph,
+ );
+ stream.handlers.on_chat_model_end.handle('on_chat_model_end', {
+ output: { tool_calls: [{ id: 'call_a', args: { sql: 'SELECT 1' } }] },
+ });
+ stream.finalizeStream();
+
+ expect(completed(events)).toEqual([
+ expect.objectContaining({
+ type: 'function_call',
+ call_id: 'call_a',
+ arguments: '{"sql":"SELECT 1"}',
+ }),
+ ]);
+ expect(
+ events
+ .filter((event) => event.type === 'response.function_call_arguments.delta')
+ .map((event) => event.delta),
+ ).toEqual(['{"sql":', '"SELECT 1"}']);
+ });
+
+ it('never eagerly answers a client-only call when its name is excluded', async () => {
+ const { events, handoff, graph, metadata, stream } = setup();
+ graph.eagerEventToolExecution = {
+ enabled: true,
+ excludeToolNames: [...handoff.clientToolNames],
+ };
+ const calls = [{ id: 'call_a', name: 'submit_sql', args: { sql: 'SELECT 1' } }];
+
+ await new ChatModelStreamHandler().handle(
+ 'on_chat_model_stream',
+ {
+ chunk: new AIMessageChunk({
+ content: '',
+ tool_calls: calls,
+ response_metadata: { finish_reason: 'tool_calls' },
+ }),
+ },
+ metadata,
+ graph,
+ );
+ stream.handlers.on_chat_model_end.handle('on_chat_model_end', {
+ output: { tool_calls: calls },
+ });
+ stream.finalizeStream();
+
+ expect(graph.eagerEventToolExecutions.size).toBe(0);
+ expect(
+ toolsCondition(
+ { messages: [{ tool_calls: calls }] } as unknown as Parameters<typeof toolsCondition>[0],
+ 'tools',
+ graph.invokedToolIds,
+ ),
+ ).not.toBe('tools');
+ expect(completed(events)).toEqual([
+ expect.objectContaining({
+ type: 'function_call',
+ call_id: 'call_a',
+ arguments: '{"sql":"SELECT 1"}',
+ }),
+ ]);
+ });
+});
diff --git a/packages/api/src/agents/responses/clientTools.spec.ts b/packages/api/src/agents/responses/clientTools.spec.ts
new file mode 100644
index 0000000000..0b1f0c94ff
--- /dev/null
+++ b/packages/api/src/agents/responses/clientTools.spec.ts
@@ -0,0 +1,528 @@
+import type {
+ LCTool,
+ StandardGraph,
+ ToolCallRequest,
+ ToolExecuteResult,
+ ToolExecuteBatchRequest,
+} from '@librechat/agents';
+import type { RunStepHandler, ToolExecuteHandler } from './clientTools';
+import type { FunctionTool, Tool } from './types';
+import {
+ validateClientTools,
+ createClientToolHandoff,
+ buildClientToolDefinitions,
+ mergeClientToolDefinitions,
+ clientToolDeferralContent,
+ createClientToolRunStepHandler,
+ createClientToolExecuteHandler,
+} from './clientTools';
+
+const fnTool = (name: string, overrides: Partial<FunctionTool> = {}): FunctionTool => ({
+ type: 'function',
+ name,
+ ...overrides,
+});
+
+describe('validateClientTools', () => {
+ it('accepts an absent, empty, or hosted-only tools list', () => {
+ expect(validateClientTools(undefined)).toBeUndefined();
+ expect(validateClientTools([])).toBeUndefined();
+ expect(validateClientTools([{ type: 'librechat:web_search' }])).toBeUndefined();
+ });
+
+ it('accepts the explicit nulls OpenAI clients send for an argumentless tool', () => {
+ expect(
+ validateClientTools([
+ { type: 'function', name: 'refresh', description: null, parameters: null },
+ ]),
+ ).toBeUndefined();
+ });
+
+ it.each<[string, unknown, string]>([
+ ['a missing name', [{ type: 'function' }], 'requires a name'],
+ ['an empty name', [fnTool('')], 'requires a name'],
+ ['an illegal character', [fnTool('open service page')], 'may contain only'],
+ ['a duplicate name', [fnTool('dup'), fnTool('dup')], 'duplicate function tool name'],
+ ['array parameters', [{ type: 'function', name: 'bad', parameters: [] }], 'JSON Schema'],
+ [
+ 'a non-string description',
+ [{ type: 'function', name: 'bad', description: 7 }],
+ 'description must be a string',
+ ],
+ [
+ 'a non-boolean strict',
+ [{ type: 'function', name: 'bad', strict: 'yes' }],
+ 'strict must be a boolean',
+ ],
+ ['a string entry', ['open_service_page'], 'tools[0] must be an object'],
+ ['a null entry', [null], 'tools[0] must be an object'],
+ ['an array entry', [[]], 'tools[0] must be an object'],
+ ['an entry without a type', [{ name: 'no_type' }], 'tools[0] must be an object'],
+ ['a non-string type', [{ type: 7 }], 'tools[0] must be an object'],
+ ['a later malformed entry', [fnTool('ok'), 'nope'], 'tools[1] must be an object'],
+ ])('rejects %s', (_label, tools, expected) => {
+ expect(validateClientTools(tools)).toContain(expected);
+ });
+
+ it('rejects a non-array tools value', () => {
+ expect(validateClientTools({})).toBe('tools must be an array');
+ });
+});
+
+describe('buildClientToolDefinitions', () => {
+ it('converts a function tool into a model-visible definition', () => {
+ const parameters = {
+ type: 'object',
+ properties: { serviceId: { type: 'string' } },
+ required: ['serviceId'],
+ };
+
+ expect(
+ buildClientToolDefinitions([
+ fnTool('open_service_page', { description: 'Open a service page', parameters }),
+ ]),
+ ).toEqual([
+ {
+ name: 'open_service_page',
+ description: 'Open a service page',
+ parameters,
+ allowed_callers: ['direct'],
+ },
+ ]);
+ });
+
+ /** The single-call instruction is added by the merge, which is the only
+ * place that knows whether a server tool exists to be batched with. */
+ it('carries the caller’s description verbatim', () => {
+ const [definition] = buildClientToolDefinitions([
+ fnTool('open_service_page', { description: 'Open a service page' }),
+ ]);
+
+ expect(definition.description).toBe('Open a service page');
+ });
+
+ it('leaves the description absent when the caller declared none', () => {
+ const [definition] = buildClientToolDefinitions([fnTool('refresh')]);
+ expect(definition.description).toBeUndefined();
+ });
+
+ it('defaults a parameterless tool to an empty JSON Schema object', () => {
+ const [definition] = buildClientToolDefinitions([fnTool('refresh')]);
+ expect(definition.parameters).toEqual({ type: 'object', properties: {} });
+ });
+
+ it('treats null parameters and description the same as absent ones', () => {
+ const [definition] = buildClientToolDefinitions([
+ fnTool('refresh', { description: null, parameters: null }),
+ ]);
+
+ expect(definition.parameters).toEqual({ type: 'object', properties: {} });
+ expect(definition.description).toBeUndefined();
+ });
+
+ it('ignores hosted tools, which the server owns', () => {
+ const definitions = buildClientToolDefinitions([
+ { type: 'librechat:web_search' } as Tool,
+ fnTool('open_service_page'),
+ ]);
+ expect(definitions.map((d) => d.name)).toEqual(['open_service_page']);
+ });
+
+ it('treats an absent tools list as no client tools', () => {
+ expect(buildClientToolDefinitions(undefined)).toEqual([]);
+ });
+});
+
+describe('mergeClientToolDefinitions', () => {
+ const serverTool: LCTool = { name: 'run_query', parameters: { type: 'object' } };
+
+ it('appends client definitions after the agent’s own', () => {
+ const merged = mergeClientToolDefinitions(
+ [serverTool],
+ buildClientToolDefinitions([fnTool('open_service_page')]),
+ );
+
+ expect(merged.toolDefinitions.map((d) => d.name)).toEqual(['run_query', 'open_service_page']);
+ expect([...merged.names]).toEqual(['open_service_page']);
+ expect(merged.shadowed).toEqual([]);
+ });
+
+ it('lets the server tool win a name collision, and reports it', () => {
+ const merged = mergeClientToolDefinitions(
+ [serverTool],
+ buildClientToolDefinitions([fnTool('run_query')]),
+ );
+
+ expect(merged.toolDefinitions).toEqual([serverTool]);
+ /** Not treated as a client tool, so the run will still execute the real one. */
+ expect(merged.names.size).toBe(0);
+ expect(merged.shadowed).toEqual(['run_query']);
+ });
+
+ it('asks the model to call the tool alone when the run has a server tool', () => {
+ const merged = mergeClientToolDefinitions(
+ [serverTool],
+ buildClientToolDefinitions([fnTool('open_service_page', { description: 'Open a page' })]),
+ );
+ const [, client] = merged.toolDefinitions;
+
+ expect(client.description).toContain('Open a page');
+ expect(client.description).toContain('only tool call of its turn');
+ });
+
+ it('carries the notice alone when the caller declared no description', () => {
+ const merged = mergeClientToolDefinitions(
+ [serverTool],
+ buildClientToolDefinitions([fnTool('refresh')]),
+ );
+
+ expect(merged.toolDefinitions[1].description).toContain('only tool call of its turn');
+ });
+
+ /** With no server tool every batch is client-only and hands off as issued,
+ * so there is nothing to warn the model about. */
+ it('leaves the description verbatim when the run owns no server tool', () => {
+ const merged = mergeClientToolDefinitions(
+ [],
+ buildClientToolDefinitions([fnTool('open_service_page', { description: 'Open a page' })]),
+ );
+
+ expect(merged.toolDefinitions[0].description).toBe('Open a page');
+ });
+
+ it('detects a collision against an agent other than the primary', () => {
+ const subagentTool: LCTool = { name: 'search', parameters: { type: 'object' } };
+ const merged = mergeClientToolDefinitions(
+ [serverTool],
+ buildClientToolDefinitions([fnTool('search')]),
+ [serverTool, subagentTool],
+ );
+
+ expect(merged.shadowed).toEqual(['search']);
+ expect(merged.names.size).toBe(0);
+ });
+
+ it('leaves the definitions untouched when nothing was declared', () => {
+ const existing = [serverTool];
+ expect(mergeClientToolDefinitions(existing, []).toolDefinitions).toBe(existing);
+ });
+
+ it('handles an agent with no definitions of its own', () => {
+ const merged = mergeClientToolDefinitions(undefined, [{ name: 'refresh' }]);
+ expect(merged.toolDefinitions.map((d) => d.name)).toEqual(['refresh']);
+ });
+});
+
+describe('createClientToolHandoff', () => {
+ const serverTool: LCTool = { name: 'run_query', parameters: { type: 'object' } };
+ const runStep: RunStepHandler = { handle: () => {} };
+ const toolExecute: ToolExecuteHandler = { handle: () => {} };
+
+ it('declares the caller’s function tools after the agent’s own', () => {
+ const handoff = createClientToolHandoff({
+ tools: [fnTool('open_service_page')],
+ agentDefinitions: [serverTool],
+ responseId: 'resp_1',
+ });
+
+ expect(handoff.toolDefinitions.map((d) => d.name)).toEqual(['run_query', 'open_service_page']);
+ });
+
+ it('reports the applied tools as the caller sent them, without the notice', () => {
+ const declared = fnTool('open_service_page', { description: 'Open a service page' });
+ const handoff = createClientToolHandoff({
+ tools: [declared],
+ agentDefinitions: [serverTool],
+ responseId: 'resp_1',
+ });
+
+ expect(handoff.appliedTools).toEqual([declared]);
+ expect(handoff.appliedTools[0].description).toBe('Open a service page');
+ });
+
+ it('omits a hosted tool from the applied tools, since the server ignores it', () => {
+ const handoff = createClientToolHandoff({
+ tools: [{ type: 'librechat:web_search' } as Tool, fnTool('open_service_page')],
+ agentDefinitions: [],
+ responseId: 'resp_1',
+ });
+
+ expect(handoff.appliedTools.map((t) => t.name)).toEqual(['open_service_page']);
+ });
+
+ /**
+ * The server tool wins the name, so the caller would wait for a handoff that
+ * can never arrive. Refused at ingress instead of dropped with a log line.
+ */
+ it('refuses a request that declares a name the agent already owns', () => {
+ const handoff = createClientToolHandoff({
+ tools: [fnTool('run_query'), fnTool('open_service_page')],
+ agentDefinitions: [serverTool],
+ responseId: 'resp_1',
+ });
+
+ expect(handoff.error).toContain('run_query');
+ expect(handoff.toolDefinitions).toEqual([serverTool]);
+ expect(handoff.appliedTools).toEqual([]);
+ expect([...handoff.clientToolNames]).toEqual([]);
+ });
+
+ /**
+ * The interception matches on tool name and marks calls in a graph-wide set,
+ * so a subagent's own tool would be intercepted just as the primary's is.
+ */
+ it('refuses a name owned by a subagent rather than the primary agent', () => {
+ const handoff = createClientToolHandoff({
+ tools: [fnTool('search')],
+ agentDefinitions: [serverTool],
+ serverDefinitions: [serverTool, { name: 'search' }],
+ responseId: 'resp_1',
+ });
+
+ expect(handoff.error).toContain('search');
+ expect([...handoff.clientToolNames]).toEqual([]);
+ });
+
+ it('drops strict from the echo, which the run cannot enforce', () => {
+ const handoff = createClientToolHandoff({
+ tools: [fnTool('open_service_page', { description: 'Open a page', strict: true })],
+ agentDefinitions: [serverTool],
+ responseId: 'resp_1',
+ });
+
+ expect(handoff.appliedTools).toEqual([
+ { type: 'function', name: 'open_service_page', description: 'Open a page' },
+ ]);
+ });
+
+ it('wraps both handlers once a client tool is in play', () => {
+ const handoff = createClientToolHandoff({
+ tools: [fnTool('open_service_page')],
+ agentDefinitions: [serverTool],
+ responseId: 'resp_1',
+ });
+
+ expect(handoff.wrapRunStep(runStep)).not.toBe(runStep);
+ expect(handoff.wrapToolExecute(toolExecute)).not.toBe(toolExecute);
+ });
+
+ /**
+ * The streaming lifecycle terminates a caller-executed call's item itself,
+ * which it can only do for names it can recognize. A name the agent already
+ * owns is served by the server tool, so it is not one of them.
+ */
+ it('names the caller-executed tools', () => {
+ const handoff = createClientToolHandoff({
+ tools: [fnTool('open_service_page'), fnTool('refresh')],
+ agentDefinitions: [serverTool],
+ responseId: 'resp_1',
+ });
+
+ expect([...handoff.clientToolNames]).toEqual(['open_service_page', 'refresh']);
+ });
+
+ it.each([
+ ['no tools at all', undefined],
+ ['hosted tools only', [{ type: 'librechat:web_search' } as Tool]],
+ ])('stays inert with %s', (_label, tools) => {
+ const agentDefinitions = [serverTool];
+ const handoff = createClientToolHandoff({ tools, agentDefinitions, responseId: 'resp_1' });
+
+ expect(handoff.toolDefinitions).toEqual(agentDefinitions);
+ expect(handoff.appliedTools).toEqual([]);
+ expect([...handoff.clientToolNames]).toEqual([]);
+ expect(handoff.wrapRunStep(runStep)).toBe(runStep);
+ expect(handoff.wrapToolExecute(toolExecute)).toBe(toolExecute);
+ });
+});
+
+describe('createClientToolRunStepHandler', () => {
+ const clientToolNames = new Set(['open_service_page']);
+ const step = (tool_calls: Array<{ id?: string; name?: string }>) => ({
+ stepDetails: { type: 'tool_calls', tool_calls },
+ });
+
+ const makeDelegate = () => ({ handle: jest.fn() });
+ const asGraph = (graph: { invokedToolIds?: Set<string> }) => graph as unknown as StandardGraph;
+
+ it('returns the delegate untouched when nothing was declared', () => {
+ const delegate = makeDelegate();
+ expect(createClientToolRunStepHandler({ delegate, clientToolNames: new Set() })).toBe(delegate);
+ });
+
+ it('marks only the client tool calls, after delegating', () => {
+ const delegate = makeDelegate();
+ const handler = createClientToolRunStepHandler({ delegate, clientToolNames });
+ const graph: { invokedToolIds?: Set<string> } = {};
+ const data = step([
+ { id: 'call_1', name: 'run_query' },
+ { id: 'call_2', name: 'open_service_page' },
+ ]);
+
+ handler.handle('on_run_step', data, undefined, asGraph(graph));
+
+ expect(delegate.handle).toHaveBeenCalledWith('on_run_step', data, undefined, graph);
+ expect([...(graph.invokedToolIds ?? [])]).toEqual(['call_2']);
+ });
+
+ it('adds to an existing set rather than replacing it', () => {
+ const invokedToolIds = new Set(['call_0']);
+ const graph = { invokedToolIds };
+ const handler = createClientToolRunStepHandler({ delegate: makeDelegate(), clientToolNames });
+
+ handler.handle(
+ 'on_run_step',
+ step([{ id: 'call_2', name: 'open_service_page' }]),
+ undefined,
+ asGraph(graph),
+ );
+
+ expect(graph.invokedToolIds).toBe(invokedToolIds);
+ expect([...invokedToolIds]).toEqual(['call_0', 'call_2']);
+ });
+
+ it('still delegates when there is no graph or no tool calls', () => {
+ const delegate = makeDelegate();
+ const handler = createClientToolRunStepHandler({ delegate, clientToolNames });
+ const graph: { invokedToolIds?: Set<string> } = {};
+
+ handler.handle(
+ 'on_run_step',
+ step([{ id: 'call_1', name: 'run_query' }]),
+ undefined,
+ asGraph(graph),
+ );
+ handler.handle(
+ 'on_run_step',
+ { stepDetails: { type: 'message_creation' } },
+ undefined,
+ asGraph(graph),
+ );
+ handler.handle('on_run_step', step([{ name: 'open_service_page' }]), undefined, asGraph(graph));
+ handler.handle('on_run_step', step([{ id: 'call_2', name: 'open_service_page' }]));
+
+ expect(delegate.handle).toHaveBeenCalledTimes(4);
+ expect(graph.invokedToolIds?.size ?? 0).toBe(0);
+ });
+});
+
+describe('createClientToolExecuteHandler', () => {
+ const clientToolNames = new Set(['submit_sql']);
+ const responseId = 'resp_1';
+
+ const toolCall = (id: string, name: string): ToolCallRequest => ({ id, name, args: {} });
+
+ const makeBatch = (toolCalls: ToolCallRequest[]) => {
+ const resolve = jest.fn();
+ const onResult = jest.fn();
+ const data = { toolCalls, resolve, onResult } as unknown as ToolExecuteBatchRequest;
+ return { data, resolve, onResult };
+ };
+
+ /** Stands in for the host executor: answers whatever batch it is handed. */
+ const makeDelegate = (results: ToolExecuteResult[] = []) => ({
+ handle: jest.fn((_event: string, data: ToolExecuteBatchRequest) => data.resolve(results)),
+ });
+
+ it('returns the delegate untouched when nothing was declared', () => {
+ const delegate = makeDelegate();
+ expect(
+ createClientToolExecuteHandler({
+ delegate,
+ clientToolNames: new Set(),
+ responseId,
+ }),
+ ).toBe(delegate);
+ });
+
+ it('passes a server-only batch through without touching it', () => {
+ const delegate = makeDelegate();
+ const handler = createClientToolExecuteHandler({ delegate, clientToolNames, responseId });
+ const { data, onResult } = makeBatch([toolCall('call_1', 'list_tables')]);
+
+ handler.handle('on_tool_execute', data);
+
+ expect(delegate.handle).toHaveBeenCalledWith('on_tool_execute', data);
+ expect(onResult).not.toHaveBeenCalled();
+ });
+
+ it('executes the server call and defers the client call of a mixed batch', () => {
+ const executed: ToolExecuteResult = {
+ toolCallId: 'call_1',
+ status: 'success',
+ content: 'default, analytics',
+ };
+ const delegate = makeDelegate([executed]);
+ const handler = createClientToolExecuteHandler({ delegate, clientToolNames, responseId });
+ const { data, resolve, onResult } = makeBatch([
+ toolCall('call_1', 'list_tables'),
+ toolCall('call_2', 'submit_sql'),
+ ]);
+
+ handler.handle('on_tool_execute', data);
+
+ const delegated = delegate.handle.mock.calls[0][1] as ToolExecuteBatchRequest;
+ expect(delegated.toolCalls).toEqual([toolCall('call_1', 'list_tables')]);
+
+ const deferral: ToolExecuteResult = {
+ toolCallId: 'call_2',
+ status: 'success',
+ content: clientToolDeferralContent('submit_sql'),
+ };
+ expect(resolve).toHaveBeenCalledTimes(1);
+ expect(resolve).toHaveBeenCalledWith([executed, deferral]);
+ expect(onResult).toHaveBeenCalledWith(deferral);
+ });
+
+ it('tells the model to call the tool alone rather than reporting a failure', () => {
+ const delegate = makeDelegate();
+ const handler = createClientToolExecuteHandler({ delegate, clientToolNames, responseId });
+ const { data, resolve } = makeBatch([
+ toolCall('call_1', 'list_tables'),
+ toolCall('call_2', 'submit_sql'),
+ ]);
+
+ handler.handle('on_tool_execute', data);
+
+ const [[deferral]] = resolve.mock.calls as [[ToolExecuteResult[]]];
+ const content = deferral.find((result) => result.toolCallId === 'call_2');
+ expect(content?.status).toBe('success');
+ expect(content?.content).toContain('submit_sql');
+ expect(content?.content).toContain('only tool call of its turn');
+ });
+
+ it('answers a client-only batch without reaching the delegate', () => {
+ const delegate = makeDelegate();
+ const handler = createClientToolExecuteHandler({ delegate, clientToolNames, responseId });
+ const { data, resolve } = makeBatch([toolCall('call_2', 'submit_sql')]);
+
+ handler.handle('on_tool_execute', data);
+
+ expect(delegate.handle).not.toHaveBeenCalled();
+ expect(resolve).toHaveBeenCalledWith([
+ {
+ toolCallId: 'call_2',
+ status: 'success',
+ content: clientToolDeferralContent('submit_sql'),
+ },
+ ]);
+ });
+
+ it('keeps the batch fields the delegate depends on', () => {
+ const delegate = makeDelegate();
+ const handler = createClientToolExecuteHandler({ delegate, clientToolNames, responseId });
+ const { data } = makeBatch([
+ toolCall('call_1', 'list_tables'),
+ toolCall('call_2', 'submit_sql'),
+ ]);
+ (data as ToolExecuteBatchRequest & { agentId?: string }).agentId = 'agent_7';
+
+ handler.handle('on_tool_execute', data);
+
+ const delegated = delegate.handle.mock.calls[0][1] as ToolExecuteBatchRequest & {
+ agentId?: string;
+ };
+ expect(delegated.agentId).toBe('agent_7');
+ expect(delegated.onResult).toBe(data.onResult);
+ });
+});
diff --git a/packages/api/src/agents/responses/clientTools.ts b/packages/api/src/agents/responses/clientTools.ts
new file mode 100644
index 0000000000..6bfc4e5fa7
--- /dev/null
+++ b/packages/api/src/agents/responses/clientTools.ts
@@ -0,0 +1,495 @@
+/**
+ * Client-side tool execution for the Open Responses API.
+ *
+ * A caller may declare function tools it will execute itself:
+ *
+ * POST /v1/responses
+ * { "model": "...", "input": "...",
+ * "tools": [{ "type": "function", "name": "open_service_page",
+ * "parameters": { ... } }] }
+ *
+ * Such a tool is made visible to the model but is never executed on the server.
+ * When the model calls one, the run ends and the call is handed back as a
+ * `function_call` output item. The caller executes it and continues by replaying
+ * *both* items in the next request's `input` — the `function_call` it received
+ * and the `function_call_output` it produced:
+ *
+ * POST /v1/responses
+ * { "model": "...", "tools": [...],
+ * "input": [ ...earlier items,
+ * { "type": "function_call", "call_id": "call_1",
+ * "name": "open_service_page", "arguments": "{...}" },
+ * { "type": "function_call_output", "call_id": "call_1",
+ * "output": "..." } ] }
+ *
+ * `convertInputToMessages` turns that pair into an assistant message carrying
+ * the tool call and a matching tool result, which is the adjacency providers
+ * require.
+ *
+ * Replay is the only continuation this endpoint supports for a tool exchange.
+ * `previous_response_id` does not carry one: the server persists a turn as
+ * text (`saveResponseOutput` keeps `output_text`, `saveInputMessages` keeps
+ * `role: 'user'`), so neither item survives, and the id is rejected outright
+ * with 404 unless the first request also asked for `store: true`. Sending
+ * `previous_response_id` with a bare `function_call_output` therefore produces
+ * a tool result whose call is missing.
+ *
+ * This is the stateless shape OpenAI defines: no run is suspended, nothing is
+ * checkpointed, and no per-caller state is held between the two requests.
+ *
+ * The handoff needs the client call to be the turn's only call, so each tool's
+ * description asks the model for that shape, and a batch that mixes one with a
+ * server tool is answered with the same instruction rather than executed.
+ */
+import { logger } from '@librechat/data-schemas';
+import type {
+ LCTool,
+ StandardGraph,
+ ToolCallRequest,
+ ToolExecuteResult,
+ ToolExecuteBatchRequest,
+} from '@librechat/agents';
+import type { FunctionTool, Tool } from './types';
+
+/** JSON Schema stand-in for a tool that declares no parameters. */
+const EMPTY_PARAMETERS = { type: 'object', properties: {} } as const;
+
+/**
+ * Matches the character set OpenAI accepts for function names, so a tool that
+ * works against their API works here without renaming.
+ */
+const CLIENT_TOOL_NAME_PATTERN = /^[A-Za-z0-9_-]+$/;
+
+/**
+ * Told to the model in every client tool's description.
+ *
+ * A batch that mixes a client tool with a server tool still enters the tool
+ * node (`toolsCondition` treats a turn as invoked only when *every* call on it
+ * is), so the handoff cannot happen from such a batch. This asks the model for
+ * the shape that can hand off; {@link createClientToolExecuteHandler} handles
+ * the batch that arrives anyway.
+ */
+const SINGLE_CALL_NOTICE = 'Call this tool on its own: it must be the only tool call of its turn.';
+
+/** A tool entry the caller will execute itself. */
+function isFunctionTool(tool: Tool | undefined | null): tool is FunctionTool {
+ return tool?.type === 'function';
+}
+
+/**
+ * The names the request declares as caller-executed.
+ *
+ * Read at ingress, before any agent is loaded, so validation can tell a call
+ * the caller owns from one the server does.
+ */
+export function declaredClientToolNames(tools: unknown): Set<string> {
+ const names = new Set<string>();
+ if (!Array.isArray(tools)) {
+ return names;
+ }
+ for (const tool of tools) {
+ if (isToolObject(tool) && isFunctionTool(tool) && typeof tool.name === 'string') {
+ names.add(tool.name);
+ }
+ }
+ return names;
+}
+
+/**
+ * A declarable tool entry: an object carrying a non-empty string `type`.
+ *
+ * Checked so that a malformed entry is rejected at ingress rather than being
+ * mistaken for a hosted tool and skipped.
+ */
+function isToolObject(value: unknown): value is Tool {
+ if (value == null || typeof value !== 'object' || Array.isArray(value)) {
+ return false;
+ }
+ const { type } = value as { type?: unknown };
+ return typeof type === 'string' && type !== '';
+}
+
+/**
+ * Why the request's `tools` cannot be declared, or undefined when they can.
+ *
+ * Every entry must be an object with a string `type`. Only `type: 'function'`
+ * entries are treated as client tools; the rest are hosted/provider tools that
+ * the server owns, and are left alone so that adding a client tool to a request
+ * cannot quietly disable them.
+ */
+export function validateClientTools(tools: unknown): string | undefined {
+ if (tools === undefined) {
+ return undefined;
+ }
+ if (!Array.isArray(tools)) {
+ return 'tools must be an array';
+ }
+
+ const names = new Set<string>();
+ for (let i = 0; i < tools.length; i++) {
+ const tool: unknown = tools[i];
+ if (!isToolObject(tool)) {
+ return `tools[${i}] must be an object with a string type`;
+ }
+ if (!isFunctionTool(tool)) {
+ continue;
+ }
+ const { name, description, parameters } = tool;
+
+ if (typeof name !== 'string' || name === '') {
+ return 'each function tool requires a name';
+ }
+ if (!CLIENT_TOOL_NAME_PATTERN.test(name)) {
+ return `function tool name may contain only letters, digits, underscores and hyphens: ${name}`;
+ }
+ if (names.has(name)) {
+ return `duplicate function tool name: ${name}`;
+ }
+ /** OpenAI clients send `null` for an absent description or parameter schema. */
+ if (description != null && typeof description !== 'string') {
+ return `function tool description must be a string: ${name}`;
+ }
+ if (parameters != null && (typeof parameters !== 'object' || Array.isArray(parameters))) {
+ return `function tool parameters must be a JSON Schema object: ${name}`;
+ }
+ if (tool.strict != null && typeof tool.strict !== 'boolean') {
+ return `function tool strict must be a boolean: ${name}`;
+ }
+ names.add(name);
+ }
+
+ return undefined;
+}
+
+/**
+ * The request's function tools as model-visible definitions, with no
+ * server-side executor. Assumes {@link validateClientTools} already passed.
+ *
+ * The caller's description is carried as sent; {@link mergeClientToolDefinitions}
+ * is what adds {@link SINGLE_CALL_NOTICE}, because only there is it known
+ * whether the agent has a server tool to be batched with.
+ */
+export function buildClientToolDefinitions(tools: Tool[] | undefined | null): LCTool[] {
+ if (tools == null) {
+ return [];
+ }
+ return tools.filter(isFunctionTool).map(({ name, description, parameters }) => ({
+ name,
+ ...(typeof description === 'string' && description !== '' ? { description } : {}),
+ parameters: (parameters ?? EMPTY_PARAMETERS) as LCTool['parameters'],
+ /** Callable by the model itself, and by nothing else. */
+ allowed_callers: ['direct' as const],
+ }));
+}
+
+/** The caller's description with the single-call instruction as its own sentence. */
+function withSingleCallNotice(definition: LCTool): LCTool {
+ const { description } = definition;
+ return {
+ ...definition,
+ description:
+ typeof description === 'string' && description !== ''
+ ? `${description} ${SINGLE_CALL_NOTICE}`
+ : SINGLE_CALL_NOTICE,
+ };
+}
+
+/**
+ * Appends the client tools to the run's model-visible definitions.
+ *
+ * A caller-declared name never displaces a server tool: on collision the
+ * server's definition wins and the client's is dropped, and the dropped names
+ * are reported so the request can be refused rather than left waiting for a
+ * handoff that the surviving server tool will never produce.
+ *
+ * `serverDefinitions` must cover every agent in the run, not just the primary
+ * one: the interception matches on tool name and marks calls in a graph-wide
+ * set, so a name a subagent owns collides just as a primary one does.
+ *
+ * {@link SINGLE_CALL_NOTICE} is added only when the run actually has a server
+ * tool. With none, every batch is client-only and hands off as issued, so the
+ * caller's description reaches the model exactly as written.
+ */
+export function mergeClientToolDefinitions(
+ agentDefinitions: LCTool[] | undefined,
+ clientDefinitions: LCTool[],
+ serverDefinitions: LCTool[] = agentDefinitions ?? [],
+): { toolDefinitions: LCTool[]; names: Set<string>; shadowed: string[] } {
+ const existing = agentDefinitions ?? [];
+ if (clientDefinitions.length === 0) {
+ return { toolDefinitions: existing, names: new Set<string>(), shadowed: [] };
+ }
+
+ const serverNames = new Set(serverDefinitions.map((definition) => definition.name));
+ const annotate = serverNames.size > 0;
+ const shadowed: string[] = [];
+ const accepted: LCTool[] = [];
+ const names = new Set<string>();
+
+ for (const definition of clientDefinitions) {
+ if (serverNames.has(definition.name)) {
+ shadowed.push(definition.name);
+ continue;
+ }
+ accepted.push(annotate ? withSingleCallNotice(definition) : definition);
+ names.add(definition.name);
+ }
+
+ return { toolDefinitions: [...existing, ...accepted], names, shadowed };
+}
+
+export interface RunStepHandler {
+ handle: (event: string, data: unknown, metadata?: unknown, graph?: StandardGraph) => void;
+}
+
+/**
+ * Wraps the run-step handler so that a call to a caller-declared tool ends the
+ * run instead of being executed on the server.
+ *
+ * The SDK routes a model turn to the tool node only while some tool call on the
+ * message is *not* in `graph.invokedToolIds` (`toolsCondition`); once every call
+ * is marked, the turn routes to END instead. That is exactly the semantics here
+ * — the call was invoked, by the caller rather than by us — and it is why the
+ * run stops with `status: 'completed'` rather than aborting or looping an error
+ * result back to the model.
+ *
+ * Two orderings matter. The delegate records the call first, which is what puts
+ * the `function_call` item into the response the caller receives. And the marks
+ * must land before the agent node returns: they are written from `on_run_step`,
+ * which the SDK dispatches while the model's tool calls are still streaming, so
+ * they precede routing. That second ordering is the one part of the mechanism
+ * unit tests cannot prove — it needs an integration test against the pinned SDK
+ * build.
+ *
+ * `toolsCondition` marks a turn invoked only when *every* call on it is, so a
+ * model that calls a client tool and a server tool in the same batch still
+ * enters the tool node and cannot hand off from that turn.
+ * {@link createClientToolExecuteHandler} answers the client call there with an
+ * instruction to call it alone, which the next turn can hand off.
+ */
+export function createClientToolRunStepHandler({
+ delegate,
+ clientToolNames,
+}: {
+ delegate: RunStepHandler;
+ clientToolNames: Set<string>;
+}): RunStepHandler {
+ if (clientToolNames.size === 0) {
+ return delegate;
+ }
+ return {
+ handle: (event, data, metadata, graph) => {
+ delegate.handle(event, data, metadata, graph);
+ if (graph == null) {
+ return;
+ }
+ const stepData = data as {
+ stepDetails?: { tool_calls?: Array<{ id?: string; name?: string }> };
+ };
+ const invoked = graph.invokedToolIds ?? new Set<string>();
+ for (const toolCall of stepData?.stepDetails?.tool_calls ?? []) {
+ if (
+ toolCall?.id != null &&
+ toolCall.id !== '' &&
+ clientToolNames.has(toolCall.name ?? '')
+ ) {
+ invoked.add(toolCall.id);
+ }
+ }
+ graph.invokedToolIds = invoked;
+ },
+ };
+}
+
+/**
+ * What the model is told when it calls a client tool in a batch that also holds
+ * a server tool.
+ *
+ * Returned as a successful tool result rather than an error: the call did not
+ * execute, but nothing failed, and `status: 'error'` would reach the model
+ * wrapped in the SDK's `Error: … Please fix your mistakes.` framing and count
+ * as a tool failure. The wording asks for the one shape that can hand off.
+ */
+export function clientToolDeferralContent(name: string): string {
+ return `"${name}" is executed by the caller, not by this server, so it cannot run in the same turn as another tool. Call "${name}" again as the only tool call of its turn.`;
+}
+
+export interface ToolExecuteHandler {
+ handle: (event: string, data: ToolExecuteBatchRequest) => void | Promise<void>;
+}
+
+/**
+ * Wraps the tool-execution handler so a caller-declared tool call that reached
+ * the tool node is answered with {@link clientToolDeferralContent} instead of
+ * the host's generic `Tool <name> not found`.
+ *
+ * Only a mixed batch gets here: a batch holding client calls alone is marked
+ * invoked in `on_run_step` and routes to END, so the tool node never sees it.
+ * The client-only branch below is therefore defensive, covering a batch that
+ * reaches execution despite the marking.
+ *
+ * The batch's server calls go to the delegate untouched and their results are
+ * merged with ours, because `resolve` is authoritative for the whole batch and
+ * must carry a result for every call the SDK dispatched. Results are matched by
+ * `toolCallId` rather than position, so the merge order does not matter.
+ *
+ * Deliberately uncapped: a model that keeps repeating the mixed batch is
+ * already bounded by the run's `recursionLimit`, so a counter here would add
+ * run state for a bound that exists. The warning is what makes the frequency
+ * measurable if that assumption turns out to be wrong.
+ */
+export function createClientToolExecuteHandler({
+ delegate,
+ clientToolNames,
+ responseId,
+ onDeferred,
+}: {
+ delegate: ToolExecuteHandler;
+ clientToolNames: Set<string>;
+ responseId: string;
+ /** Reports the answer given to a deferred call, so the run can show it was answered. */
+ onDeferred?: (callId: string, output: string) => void;
+}): ToolExecuteHandler {
+ if (clientToolNames.size === 0) {
+ return delegate;
+ }
+
+ return {
+ handle: (event, data) => {
+ const executable: ToolCallRequest[] = [];
+ const results: ToolExecuteResult[] = [];
+ const deferredNames: string[] = [];
+ for (const toolCall of data.toolCalls) {
+ if (!clientToolNames.has(toolCall.name)) {
+ executable.push(toolCall);
+ continue;
+ }
+ const content = clientToolDeferralContent(toolCall.name);
+ results.push({
+ toolCallId: toolCall.id,
+ status: 'success',
+ content,
+ });
+ deferredNames.push(toolCall.name);
+ onDeferred?.(toolCall.id, content);
+ }
+
+ if (results.length === 0) {
+ return delegate.handle(event, data);
+ }
+
+ logger.warn(
+ `[Responses API] Request ${responseId} called caller-executed tool(s) alongside server tools, which cannot hand off; asked the model to call them alone: ${deferredNames.join(', ')}`,
+ );
+ for (const result of results) {
+ data.onResult?.(result);
+ }
+
+ if (executable.length === 0) {
+ data.resolve(results);
+ return;
+ }
+
+ return delegate.handle(event, {
+ ...data,
+ toolCalls: executable,
+ resolve: (executed: ToolExecuteResult[]): void => data.resolve([...executed, ...results]),
+ });
+ },
+ };
+}
+
+/** Everything a run needs in order to honor the caller's function tools. */
+export interface ClientToolHandoff {
+ /** The agent's model-visible definitions with the accepted client tools appended. */
+ toolDefinitions: LCTool[];
+ /**
+ * The caller's `function` entries that reached the model. Hosted entries the
+ * server ignores are absent, and `strict` is dropped because the run has no
+ * way to enforce it -- so echoing this on the response describes the tools
+ * the run actually ran with rather than the request's ask.
+ */
+ appliedTools: FunctionTool[];
+ /** Why the request's tools cannot be honored, or undefined when they can. */
+ error?: string;
+ /**
+ * The names the model sees as caller-executed. The streaming lifecycle needs
+ * them to recognize a call the server will never run, and so never close
+ * through `on_tool_end`. Empty when the request declared none.
+ */
+ clientToolNames: ReadonlySet<string>;
+ wrapRunStep: (delegate: RunStepHandler) => RunStepHandler;
+ wrapToolExecute: (
+ delegate: ToolExecuteHandler,
+ onDeferred?: (callId: string, output: string) => void,
+ ) => ToolExecuteHandler;
+}
+
+const identity = <T>(delegate: T): T => delegate;
+
+/**
+ * Assembles the client-tool handoff for one request: what the model sees, what
+ * the response should report, and the two handler wrappers that hand a call
+ * back to the caller.
+ *
+ * Built in one place so a request path only wires it in. A request that
+ * declares no function tool gets the agent's definitions unchanged and identity
+ * wrappers, so the common request pays nothing.
+ *
+ * Assumes {@link validateClientTools} already passed at ingress.
+ */
+export function createClientToolHandoff({
+ tools,
+ agentDefinitions,
+ serverDefinitions,
+ responseId,
+}: {
+ tools?: Tool[] | null;
+ agentDefinitions?: LCTool[];
+ /** Every agent's definitions, primary and subagents alike; defaults to the primary's. */
+ serverDefinitions?: LCTool[];
+ responseId: string;
+}): ClientToolHandoff {
+ const declared = buildClientToolDefinitions(tools);
+ if (declared.length === 0) {
+ return {
+ toolDefinitions: agentDefinitions ?? [],
+ appliedTools: [],
+ clientToolNames: new Set<string>(),
+ wrapRunStep: identity,
+ wrapToolExecute: identity,
+ };
+ }
+
+ const { toolDefinitions, names, shadowed } = mergeClientToolDefinitions(
+ agentDefinitions,
+ declared,
+ serverDefinitions ?? agentDefinitions ?? [],
+ );
+
+ /* Refused rather than dropped with a warning: the server tool wins the name,
+ so the caller would wait for a handoff that can never arrive. */
+ if (shadowed.length > 0) {
+ return {
+ toolDefinitions: agentDefinitions ?? [],
+ appliedTools: [],
+ clientToolNames: new Set<string>(),
+ wrapRunStep: identity,
+ wrapToolExecute: identity,
+ error:
+ `function tool name is already provided by this agent: ${shadowed.join(', ')}; ` +
+ 'rename the tool or remove it from the request',
+ };
+ }
+
+ return {
+ toolDefinitions,
+ appliedTools: (tools ?? [])
+ .filter((tool): tool is FunctionTool => isFunctionTool(tool) && names.has(tool.name))
+ .map(({ strict: _strict, ...applied }) => applied),
+ clientToolNames: names,
+ wrapRunStep: (delegate) => createClientToolRunStepHandler({ delegate, clientToolNames: names }),
+ wrapToolExecute: (delegate, onDeferred) =>
+ createClientToolExecuteHandler({ delegate, clientToolNames: names, responseId, onDeferred }),
+ };
+}
diff --git a/packages/api/src/agents/responses/handlers.ts b/packages/api/src/agents/responses/handlers.ts
index 1aa6ec45af..83bcf34556 100644
--- a/packages/api/src/agents/responses/handlers.ts
+++ b/packages/api/src/agents/responses/handlers.ts
@@ -142,7 +142,7 @@ export function buildResponse(
instructions: context.instructions ?? null,
output: tracker.items,
error: null,
- tools: [],
+ tools: context.tools ?? [],
tool_choice: 'auto',
truncation: 'disabled',
parallel_tool_calls: true,
@@ -278,6 +278,13 @@ export interface StreamHandlerConfig {
res: ServerResponse;
context: ResponseContext;
tracker: ResponseTracker;
+ /**
+ * Names the caller declared and executes itself. A call to one of these is
+ * never run by the server, so `on_tool_end` cannot terminate its item and the
+ * run's own finalization has to. Omitted by every request that declares none,
+ * which leaves that request's event stream untouched.
+ */
+ clientToolNames?: ReadonlySet<string>;
}
/**
diff --git a/packages/api/src/agents/responses/index.ts b/packages/api/src/agents/responses/index.ts
index af9c4cece8..692174a4c7 100644
--- a/packages/api/src/agents/responses/index.ts
+++ b/packages/api/src/agents/responses/index.ts
@@ -182,3 +182,6 @@ export {
createAggregatorEventHandlers,
type ResponseAggregator,
} from './service';
+
+// Client-side tool execution
+export { createClientToolHandoff, type ClientToolHandoff } from './clientTools';
diff --git a/packages/api/src/agents/responses/service.ts b/packages/api/src/agents/responses/service.ts
index 4a0f74d165..ccd44ba4bf 100644
--- a/packages/api/src/agents/responses/service.ts
+++ b/packages/api/src/agents/responses/service.ts
@@ -4,10 +4,16 @@
* Core service for processing Open Responses API requests.
* Handles input conversion, message formatting, and request validation.
*/
-import { isCodeEnvironmentMode, isCodeWorkspaceSelections } from 'librechat-data-provider';
+import {
+ ContentTypes,
+ isCodeEnvironmentMode,
+ isCodeWorkspaceSelections,
+} from 'librechat-data-provider';
import type { Response as ServerResponse } from 'express';
import type {
+ FunctionCallOutputItemParam,
RequestValidationResult,
+ FunctionCallItemParam,
ResponseRequest,
ResponseContext,
InputContent,
@@ -39,6 +45,7 @@ import {
emitReasoningItemDone,
type StreamHandlerConfig,
} from './handlers';
+import { declaredClientToolNames, validateClientTools } from './clientTools';
import { aggregateCollectedUsage } from '../usage';
interface ResponseUsageAccumulator {
@@ -136,9 +143,111 @@ export function validateResponseRequest(body: unknown): RequestValidationResult
return { valid: false, error: 'previous_response_id must be a string' };
}
+ const clientToolsError = validateClientTools(request.tools);
+ if (clientToolsError !== undefined) {
+ return { valid: false, error: clientToolsError };
+ }
+
+ if (Array.isArray(request.input)) {
+ const toolExchangeError = validateInputToolExchanges(
+ request.input as InputItem[],
+ declaredClientToolNames(request.tools),
+ );
+ if (toolExchangeError !== undefined) {
+ return { valid: false, error: toolExchangeError };
+ }
+ }
+
return { valid: true, request: request as unknown as ResponseRequest };
}
+function isNonEmptyString(value: unknown): value is string {
+ return typeof value === 'string' && value !== '';
+}
+
+/**
+ * Validates the replayed tool exchanges in `input`.
+ *
+ * A turn is persisted as text, so `previous_response_id` does not carry a tool
+ * exchange: replaying the `function_call` together with its
+ * `function_call_output` is the only supported continuation. For a tool the
+ * caller executes, both halves are therefore required, and an unpaired half is
+ * the caller's error rather than something to hand to the provider — an
+ * unanswered tool call reaches the model as a malformed conversation and comes
+ * back as an opaque upstream failure.
+ *
+ * A call to a tool the *server* owns is not held to that rule. The server emits
+ * a `function_call` for its own tools but no `function_call_output`, so the
+ * usual continuation — appending the previous response's `output` to the next
+ * request's `input` — carries calls the caller cannot answer and never could.
+ * Those are dropped in {@link convertInputToMessages} instead of refused here.
+ *
+ * @returns An error message, or `undefined` when every exchange is well formed.
+ */
+export function validateInputToolExchanges(
+ input: InputItem[],
+ clientToolNames: ReadonlySet<string> = new Set<string>(),
+): string | undefined {
+ const callIds = new Set<string>();
+ const clientCallIds = new Set<string>();
+ const outputCallIds = new Set<string>();
+
+ for (const item of input) {
+ if (item == null || typeof item !== 'object') {
+ continue;
+ }
+
+ if (item.type === 'function_call') {
+ const call = item as Partial<FunctionCallItemParam>;
+ if (!isNonEmptyString(call.call_id)) {
+ return 'each function_call requires a non-empty string call_id';
+ }
+ if (!isNonEmptyString(call.name)) {
+ return `function_call ${call.call_id} requires a non-empty string name`;
+ }
+ if (typeof call.arguments !== 'string') {
+ return `function_call ${call.call_id} requires arguments as a JSON string`;
+ }
+ if (callIds.has(call.call_id)) {
+ return `duplicate function_call call_id: ${call.call_id}`;
+ }
+ callIds.add(call.call_id);
+ if (clientToolNames.has(call.name)) {
+ clientCallIds.add(call.call_id);
+ }
+ continue;
+ }
+
+ if (item.type === 'function_call_output') {
+ const output = item as Partial<FunctionCallOutputItemParam>;
+ if (!isNonEmptyString(output.call_id)) {
+ return 'each function_call_output requires a non-empty string call_id';
+ }
+ if (typeof output.output !== 'string') {
+ return `function_call_output ${output.call_id} requires output as a string`;
+ }
+ if (outputCallIds.has(output.call_id)) {
+ return `duplicate function_call_output call_id: ${output.call_id}`;
+ }
+ outputCallIds.add(output.call_id);
+ }
+ }
+
+ for (const callId of clientCallIds) {
+ if (!outputCallIds.has(callId)) {
+ return `function_call ${callId} has no function_call_output in input; replay both items to continue a tool exchange`;
+ }
+ }
+
+ for (const callId of outputCallIds) {
+ if (!callIds.has(callId)) {
+ return `function_call_output ${callId} has no matching function_call in input`;
+ }
+ }
+
+ return undefined;
+}
+
/**
* Check if validation failed
*/
@@ -152,17 +261,34 @@ export function isValidationFailure(
* INPUT CONVERSION
* ============================================================================= */
-/** Internal message format (LibreChat-compatible) */
+/** A replayed tool exchange, in the content-part shape LibreChat persists. */
+export interface InternalToolCallPart {
+ type: ContentTypes.TOOL_CALL;
+ tool_call: {
+ id: string;
+ name: string;
+ /** Raw JSON string as the caller sent it; `formatAgentMessages` parses it. */
+ args: string;
+ /** The caller's result for this call. Present on every replayed pair. */
+ output: string;
+ };
+}
+
+/**
+ * Internal message format (LibreChat-compatible).
+ *
+ * There is deliberately no `tool` role and no `tool_call_id`: a tool result
+ * belongs to the `tool_call` part of the assistant turn that made the call.
+ * `formatMessage` has no branch for a tool role, so such a message formats as a
+ * SystemMessage and breaks the conversation for providers that accept a system
+ * message only in first position.
+ */
export interface InternalMessage {
- role: 'system' | 'user' | 'assistant' | 'tool';
- content: string | Array<{ type: string; text?: string; image_url?: unknown }>;
+ role: 'system' | 'user' | 'assistant';
+ content:
+ | string
+ | Array<{ type: string; text?: string; image_url?: unknown } | InternalToolCallPart>;
name?: string;
- tool_call_id?: string;
- tool_calls?: Array<{
- id: string;
- type: 'function';
- function: { name: string; arguments: string };
- }>;
}
/**
@@ -176,6 +302,14 @@ export function convertInputToMessages(input: string | InputItem[]): InternalMes
}
const messages: InternalMessage[] = [];
+ const outputsByCallId = collectFunctionCallOutputs(input);
+ /**
+ * The assistant message collecting the current run of consecutive
+ * `function_call` items. A parallel batch arrives as several calls in a row
+ * and belongs on ONE assistant turn, so providers that pair tool results
+ * against the calls of a single turn see the batch as it was issued.
+ */
+ let pendingToolCallMessage: InternalMessage | null = null;
for (const item of input) {
if (item.type === 'item_reference') {
@@ -183,6 +317,10 @@ export function convertInputToMessages(input: string | InputItem[]): InternalMes
continue;
}
+ if (item.type !== 'function_call') {
+ pendingToolCallMessage = null;
+ }
+
if (item.type === 'message') {
const messageItem = item as {
type: 'message';
@@ -241,38 +379,47 @@ export function convertInputToMessages(input: string | InputItem[]): InternalMes
messages.push({ role, content });
}
+ /**
+ * A replayed call and its result become ONE `tool_call` content part on an
+ * assistant message, which is how LibreChat persists a tool exchange and
+ * the only shape `formatAgentMessages` reads: it emits the provider's
+ * tool-use block from the part and the paired tool result from
+ * `tool_call.output`. The OpenAI-style `{ role: 'tool' }` message this
+ * used to produce has no branch in `formatMessage`, which turned it into a
+ * SystemMessage mid-conversation — rejected outright by providers that
+ * allow a system message only as the first one.
+ *
+ * `function_call_output` items are consumed here through `outputsByCallId`,
+ * not emitted on their own; ingress validation has already established
+ * that a caller-executed call has exactly one output and vice versa.
+ *
+ * A call with no output is one of the server's own, replayed from a
+ * previous response that never carried a result for it. It is dropped:
+ * replaying it with an empty result would put an unanswered tool call in
+ * front of the provider, which is what the pairing rule exists to prevent.
+ */
if (item.type === 'function_call') {
- // Function call items represent prior tool calls from assistant
- const fcItem = item as {
- type: 'function_call';
- call_id: string;
- name: string;
- arguments: string;
+ const fcItem = item as FunctionCallItemParam;
+ const output = outputsByCallId.get(fcItem.call_id);
+ if (output === undefined) {
+ continue;
+ }
+ const part: InternalToolCallPart = {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id: fcItem.call_id,
+ name: fcItem.name,
+ args: fcItem.arguments,
+ output,
+ },
};
- // Add as assistant message with tool_calls
- messages.push({
- role: 'assistant',
- content: '',
- tool_calls: [
- {
- id: fcItem.call_id,
- type: 'function',
- function: { name: fcItem.name, arguments: fcItem.arguments },
- },
- ],
- });
- }
-
- if (item.type === 'function_call_output') {
- // Function call output items represent tool results
- const fcoItem = item as { type: 'function_call_output'; call_id: string; output: string };
-
- messages.push({
- role: 'tool',
- content: fcoItem.output,
- tool_call_id: fcoItem.call_id,
- });
+ if (pendingToolCallMessage != null && Array.isArray(pendingToolCallMessage.content)) {
+ pendingToolCallMessage.content.push(part);
+ } else {
+ pendingToolCallMessage = { role: 'assistant', content: [part] };
+ messages.push(pendingToolCallMessage);
+ }
}
// Reasoning items are typically not passed back as input
@@ -282,6 +429,18 @@ export function convertInputToMessages(input: string | InputItem[]): InternalMes
return messages;
}
+/** Indexes every `function_call_output` in the input by its `call_id`. */
+function collectFunctionCallOutputs(input: InputItem[]): Map<string, string> {
+ const outputs = new Map<string, string>();
+ for (const item of input) {
+ if (item.type === 'function_call_output') {
+ const fcoItem = item as FunctionCallOutputItemParam;
+ outputs.set(fcoItem.call_id, fcoItem.output);
+ }
+ }
+ return outputs;
+}
+
/**
* Merge previous conversation messages with new input
*/
@@ -372,6 +531,91 @@ interface StreamState {
reasoningContentStarted: boolean;
activeToolCalls: Set<string>;
completedToolCalls: Set<string>;
+ /** Calls to a caller-executed tool — the subset the run has to terminate itself. */
+ clientToolCalls: Set<string>;
+}
+
+/** One streamed argument fragment, as the agents SDK forwards LangChain tool call chunks. */
+interface ToolCallChunk {
+ id?: string;
+ index?: number;
+ args?: string;
+}
+
+/**
+ * Arguments as they appear on a completed model message, keyed by call id.
+ *
+ * The agents SDK only streams argument fragments when the provider sends the call in pieces; a
+ * call that arrives whole is dispatched with its arguments already parsed and no deltas follow.
+ * The completed message carries both cases, so it is the reliable source for any call whose
+ * arguments never arrived as fragments.
+ */
+function completedToolCallArguments(data: unknown): Array<{ id: string; args: string }> {
+ const endData = data as { output?: { tool_calls?: Array<{ id?: string; args?: unknown }> } };
+ const toolCalls = endData?.output?.tool_calls;
+ if (!Array.isArray(toolCalls)) {
+ return [];
+ }
+
+ const resolved: Array<{ id: string; args: string }> = [];
+ for (const tc of toolCalls) {
+ const id = tc.id ?? '';
+ if (!id || tc.args == null) {
+ continue;
+ }
+ resolved.push({ id, args: typeof tc.args === 'string' ? tc.args : JSON.stringify(tc.args) });
+ }
+ return resolved;
+}
+
+interface ToolCallChunkResolver {
+ registerStep: (stepId: string, callIds: string[]) => void;
+ resolve: (stepId: string, chunk: ToolCallChunk) => string | undefined;
+}
+
+/**
+ * Matches a streamed argument fragment to the tool call it belongs to.
+ *
+ * A chunk's `index` is provider-relative: Anthropic numbers content blocks, so thinking and text
+ * blocks consume values, and the numbering restarts on every step. It is therefore not an offset
+ * into the run's tool calls, and using it as one appends arguments to the wrong call as soon as a
+ * run makes more than one. Chunks are matched by id, falling back to the index recorded alongside
+ * that id within the same step, and finally to a step that holds exactly one call.
+ */
+function createToolCallChunkResolver(): ToolCallChunkResolver {
+ const indexToCallId = new Map<string, Map<number, string>>();
+ const stepCallIds = new Map<string, string[]>();
+
+ return {
+ registerStep: (stepId: string, callIds: string[]): void => {
+ stepCallIds.set(stepId, callIds);
+ },
+
+ resolve: (stepId: string, chunk: ToolCallChunk): string | undefined => {
+ let byIndex = indexToCallId.get(stepId);
+ if (!byIndex) {
+ byIndex = new Map<number, string>();
+ indexToCallId.set(stepId, byIndex);
+ }
+
+ if (chunk.id != null && chunk.id !== '') {
+ if (chunk.index != null) {
+ byIndex.set(chunk.index, chunk.id);
+ }
+ return chunk.id;
+ }
+
+ if (chunk.index != null) {
+ const mapped = byIndex.get(chunk.index);
+ if (mapped != null) {
+ return mapped;
+ }
+ }
+
+ const callIds = stepCallIds.get(stepId);
+ return callIds?.length === 1 ? callIds[0] : undefined;
+ },
+ };
}
/**
@@ -381,6 +625,7 @@ export function createResponsesEventHandlers(config: StreamHandlerConfig): {
handlers: Record<string, { handle: (event: string, data: unknown) => void }>;
state: StreamState;
finalizeStream: (usage?: Usage) => void;
+ emitClientToolDeferral: (callId: string, output: string) => void;
} {
const state: StreamState = {
messageStarted: false,
@@ -389,8 +634,13 @@ export function createResponsesEventHandlers(config: StreamHandlerConfig): {
reasoningContentStarted: false,
activeToolCalls: new Set(),
completedToolCalls: new Set(),
+ clientToolCalls: new Set(),
};
+ const chunkResolver = createToolCallChunkResolver();
+ let modelEndedClientCalls: Set<string> | undefined;
+ let pendingClientToolDeferrals: Map<string, string> | undefined;
+
/**
* Ensure message item is started
*/
@@ -433,6 +683,73 @@ export function createResponsesEventHandlers(config: StreamHandlerConfig): {
}
};
+ /**
+ * Closes a caller-executed call that the server answered itself, and emits
+ * the answer as a `function_call_output` item.
+ *
+ * Without the output item the call is indistinguishable from one handed back
+ * for the caller to run, so a caller would execute a tool the model was told
+ * to re-issue — and a side-effecting tool would run twice.
+ */
+ const deliverClientToolDeferral = (callId: string, output: string): void => {
+ if (state.completedToolCalls.has(callId)) {
+ return;
+ }
+ state.completedToolCalls.add(callId);
+ emitFunctionCallArgumentsDone(config, callId);
+ emitFunctionCallItemDone(config, callId);
+ emitFunctionCallOutputItem(config, callId, output);
+ };
+
+ const emitClientToolDeferral = (callId: string, output: string): void => {
+ if (!state.activeToolCalls.has(callId) || state.completedToolCalls.has(callId)) {
+ return;
+ }
+ // A tool-execute event can beat the model-end event that contains the
+ // authoritative arguments. Keep the result pending until they arrive.
+ if (modelEndedClientCalls?.has(callId)) {
+ deliverClientToolDeferral(callId, output);
+ return;
+ }
+ (pendingClientToolDeferrals ??= new Map()).set(callId, output);
+ };
+
+ /**
+ * Terminate the still-open calls to a caller-executed tool.
+ *
+ * `on_tool_end` terminates a call the server ran, which a caller-executed
+ * tool never is — the whole point is that the server hands it back. Without
+ * this, a streaming caller gets `output_item.added` plus argument deltas and
+ * then `response.completed`, with no `function_call_arguments.done` to mark
+ * the arguments final, and the item it is expected to act on stays
+ * `in_progress` inside a response that claims to be completed. A caller that
+ * waits for the terminating event before running the tool, as the streaming
+ * lifecycle tells it to, would wait forever.
+ *
+ * Deliberately limited to those calls. A server tool left open is the
+ * separate, pre-existing symptom of `on_tool_end` never reaching this module
+ * (the controller replaces the handler rather than composing with it); fixing
+ * that belongs at the wiring, not here, and closing such calls from
+ * finalization would change the event stream of every request that declares
+ * no client tool.
+ *
+ * Idempotent in both directions: a call already closed by `on_tool_end` is
+ * skipped, and marking it closed keeps `on_tool_end` from emitting a second
+ * pair afterwards. Arguments are complete by this point — `on_chat_model_end`
+ * backfills a delta for any call whose arguments the provider sent whole
+ * rather than streamed.
+ */
+ const closeOpenClientToolCalls = (): void => {
+ for (const callId of state.clientToolCalls) {
+ if (state.completedToolCalls.has(callId)) {
+ continue;
+ }
+ state.completedToolCalls.add(callId);
+ emitFunctionCallArgumentsDone(config, callId);
+ emitFunctionCallItemDone(config, callId);
+ }
+ };
+
/**
* Close any open content streams
*/
@@ -512,6 +829,7 @@ export function createResponsesEventHandlers(config: StreamHandlerConfig): {
on_run_step: {
handle: (_event: string, data: unknown): void => {
const stepData = data as {
+ id?: string;
stepDetails?: { type: string; tool_calls?: Array<{ id?: string; name?: string }> };
};
const stepDetails = stepData?.stepDetails;
@@ -520,15 +838,28 @@ export function createResponsesEventHandlers(config: StreamHandlerConfig): {
// Close any open message/reasoning before tool calls
closeOpenStreams();
+ const stepCallIds: string[] = [];
for (const tc of stepDetails.tool_calls) {
const callId = tc.id ?? '';
const name = tc.name ?? '';
- if (callId && !state.activeToolCalls.has(callId)) {
+ if (!callId) {
+ continue;
+ }
+
+ stepCallIds.push(callId);
+ if (!state.activeToolCalls.has(callId)) {
state.activeToolCalls.add(callId);
+ /* Recorded at announcement, while the name is in hand: the
+ terminating events are emitted much later, from finalization,
+ where only the call id is available. */
+ if (config.clientToolNames?.has(name) === true) {
+ state.clientToolCalls.add(callId);
+ }
emitFunctionCallItemAdded(config, callId, name);
}
}
+ chunkResolver.registerStep(stepData?.id ?? '', stepCallIds);
}
},
},
@@ -539,24 +870,21 @@ export function createResponsesEventHandlers(config: StreamHandlerConfig): {
on_run_step_delta: {
handle: (_event: string, data: unknown): void => {
const deltaData = data as {
- delta?: { type: string; tool_calls?: Array<{ index?: number; args?: string }> };
+ id?: string;
+ delta?: { type: string; tool_calls?: ToolCallChunk[] };
};
const delta = deltaData?.delta;
if (delta?.type === 'tool_calls' && delta.tool_calls) {
for (const tc of delta.tool_calls) {
- const args = tc.args ?? '';
- if (!args) {
+ // Resolved before the empty-args check so an id-bearing opening chunk is recorded.
+ const callId = chunkResolver.resolve(deltaData?.id ?? '', tc);
+ const args = typeof tc.args === 'string' ? tc.args : '';
+ if (!args || !callId) {
continue;
}
- // Find the call_id for this tool call by index
- const toolCallsArray = Array.from(state.activeToolCalls);
- const callId = toolCallsArray[tc.index ?? 0];
-
- if (callId) {
- emitFunctionCallArgumentsDelta(config, callId, args);
- }
+ emitFunctionCallArgumentsDelta(config, callId, args);
}
}
},
@@ -599,6 +927,27 @@ export function createResponsesEventHandlers(config: StreamHandlerConfig): {
if (usage) {
accumulateResponseUsage(config.tracker.usage, usage);
}
+
+ for (const { id, args } of completedToolCallArguments(data)) {
+ if (!state.activeToolCalls.has(id)) {
+ continue;
+ }
+ const streamed = config.tracker.accumulatedArguments.get(id) ?? '';
+ // An early handoff mark changes the SDK's step key. If a later
+ // index-only chunk lands on that new step, recover just the missing
+ // suffix without duplicating fragments already sent over SSE.
+ if (args.startsWith(streamed) && args.length > streamed.length) {
+ emitFunctionCallArgumentsDelta(config, id, args.slice(streamed.length));
+ }
+ if (state.clientToolCalls.has(id)) {
+ (modelEndedClientCalls ??= new Set()).add(id);
+ const deferred = pendingClientToolDeferrals?.get(id);
+ if (deferred !== undefined) {
+ pendingClientToolDeferrals?.delete(id);
+ deliverClientToolDeferral(id, deferred);
+ }
+ }
+ }
},
},
};
@@ -608,11 +957,17 @@ export function createResponsesEventHandlers(config: StreamHandlerConfig): {
*/
const finalizeStream = (usage?: Usage): void => {
closeOpenStreams();
+ for (const [callId, output] of pendingClientToolDeferrals ?? []) {
+ deliverClientToolDeferral(callId, output);
+ }
+ // A later step can announce a sibling before its arguments or deferral
+ // are settled. Only terminate handoffs after the run has completed.
+ closeOpenClientToolCalls();
emitResponseCompleted(config, usage);
writeDone(config.res);
};
- return { handlers, state, finalizeStream };
+ return { handlers, state, finalizeStream, emitClientToolDeferral };
}
/* =============================================================================
@@ -744,7 +1099,8 @@ export function buildAggregatedResponse(
instructions: context.instructions ?? null,
output,
error: null,
- tools: [],
+ tools: context.tools ?? [],
+ /** Not forwarded to the model, so reporting the request's ask would misstate the run. */
tool_choice: 'auto',
truncation: 'disabled',
parallel_tool_calls: true,
@@ -808,6 +1164,7 @@ export function createAggregatorEventHandlers(aggregator: ResponseAggregator): R
}
> {
const activeToolCalls = new Set<string>();
+ const chunkResolver = createToolCallChunkResolver();
return {
on_message_delta: {
@@ -846,20 +1203,33 @@ export function createAggregatorEventHandlers(aggregator: ResponseAggregator): R
on_run_step: {
handle: (_event: string, data: unknown): void => {
const stepData = data as {
- stepDetails?: { type: string; tool_calls?: Array<{ id?: string; name?: string }> };
+ id?: string;
+ stepDetails?: {
+ type: string;
+ tool_calls?: Array<{ id?: string; name?: string; args?: unknown }>;
+ };
};
const stepDetails = stepData?.stepDetails;
if (stepDetails?.type === 'tool_calls' && stepDetails.tool_calls) {
+ const stepCallIds: string[] = [];
for (const tc of stepDetails.tool_calls) {
const callId = tc.id ?? '';
const name = tc.name ?? '';
- if (callId && !activeToolCalls.has(callId)) {
+ if (!callId) {
+ continue;
+ }
+
+ stepCallIds.push(callId);
+ if (!activeToolCalls.has(callId)) {
activeToolCalls.add(callId);
- aggregator.toolCalls.set(callId, { id: callId, name, arguments: '' });
+ // A provider that does not stream its arguments delivers them here instead.
+ const seeded = typeof tc.args === 'string' ? tc.args : '';
+ aggregator.toolCalls.set(callId, { id: callId, name, arguments: seeded });
}
}
+ chunkResolver.registerStep(stepData?.id ?? '', stepCallIds);
}
},
},
@@ -867,25 +1237,23 @@ export function createAggregatorEventHandlers(aggregator: ResponseAggregator): R
on_run_step_delta: {
handle: (_event: string, data: unknown): void => {
const deltaData = data as {
- delta?: { type: string; tool_calls?: Array<{ index?: number; args?: string }> };
+ id?: string;
+ delta?: { type: string; tool_calls?: ToolCallChunk[] };
};
const delta = deltaData?.delta;
if (delta?.type === 'tool_calls' && delta.tool_calls) {
for (const tc of delta.tool_calls) {
- const args = tc.args ?? '';
- if (!args) {
+ // Resolved before the empty-args check so an id-bearing opening chunk is recorded.
+ const callId = chunkResolver.resolve(deltaData?.id ?? '', tc);
+ const args = typeof tc.args === 'string' ? tc.args : '';
+ if (!args || !callId) {
continue;
}
- const toolCallsArray = Array.from(activeToolCalls);
- const callId = toolCallsArray[tc.index ?? 0];
-
- if (callId) {
- const existing = aggregator.toolCalls.get(callId);
- if (existing) {
- existing.arguments += args;
- }
+ const existing = aggregator.toolCalls.get(callId);
+ if (existing) {
+ existing.arguments += args;
}
}
}
@@ -916,6 +1284,13 @@ export function createAggregatorEventHandlers(aggregator: ResponseAggregator): R
if (usage) {
accumulateResponseUsage(aggregator.usage, usage);
}
+
+ for (const { id, args } of completedToolCallArguments(data)) {
+ const existing = aggregator.toolCalls.get(id);
+ if (existing && existing.arguments === '') {
+ existing.arguments = args;
+ }
+ }
},
},
};
diff --git a/packages/api/src/agents/responses/types.ts b/packages/api/src/agents/responses/types.ts
index 161adc4f90..e7e7b5bb80 100644
--- a/packages/api/src/agents/responses/types.ts
+++ b/packages/api/src/agents/responses/types.ts
@@ -275,8 +275,8 @@ export type OutputItem = MessageItem | FunctionCallItem | FunctionCallOutputItem
export interface FunctionTool {
type: 'function';
name: string;
- description?: string;
- parameters?: Record<string, unknown>;
+ description?: string | null;
+ parameters?: Record<string, unknown> | null;
strict?: boolean;
}
@@ -783,6 +783,11 @@ export interface ResponseContext {
previousResponseId?: string;
/** Instructions */
instructions?: string;
+ /**
+ * The caller's function tools that were actually declared to the model,
+ * echoed back on the response. Absent until the run resolves them.
+ */
+ tools?: FunctionTool[];
}
/** Validation result for requests */
diff --git a/packages/api/src/agents/run.ts b/packages/api/src/agents/run.ts
index 27a00ff223..8e010a21fb 100644
--- a/packages/api/src/agents/run.ts
+++ b/packages/api/src/agents/run.ts
@@ -2104,6 +2104,7 @@ export async function createRun({
compactionSemanticIndex,
initialSummary,
modelCallbacks,
+ clientToolNames,
calibrationRatio,
fadingTier,
fadingTiers,
@@ -2170,6 +2171,8 @@ export async function createRun({
initialSummary?: { text: string; tokenCount: number };
/** Model callbacks inherited by root, summary, fallback, and subagent clients. */
modelCallbacks?: readonly RunModelCallback[];
+ /** Caller-executed tools must never run eagerly before handoff is decided. */
+ clientToolNames?: ReadonlySet<string>;
/** Calibration ratio from previous run's contextMeta, seeds the pruner EMA */
calibrationRatio?: number;
/**
@@ -2947,6 +2950,7 @@ export async function createRun({
*/
CHECK_BACKGROUND_TASK_NAME,
...agents.flatMap((agent) => agent.backgroundToolNames ?? []),
+ ...(clientToolNames ?? []),
],
},
// Let host file tools share the code-execution sandbox session so a file