Skip to content

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

🔨 chore(api): add POST /api/agent/tool-result callback endpoint (#13764)

Arvin Xuc60563fffc19
diff --git a/src/app/(backend)/api/agent/tool-result/__tests__/route.test.ts b/src/app/(backend)/api/agent/tool-result/__tests__/route.test.ts
new file mode 100644
index 00000000000..cbe9d0f6f5a
--- /dev/null
+++ b/src/app/(backend)/api/agent/tool-result/__tests__/route.test.ts
@@ -0,0 +1,99 @@
+// @vitest-environment node
+import { NextRequest } from 'next/server';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { POST } from '../route';
+
+// Mock dependencies before import usage
+const mockPipelineExec = vi.fn().mockResolvedValue([]);
+const mockExpire = vi.fn(() => ({ exec: mockPipelineExec }));
+const mockLpush = vi.fn(() => ({ expire: mockExpire }));
+const mockPipeline = vi.fn(() => ({ lpush: mockLpush }));
+
+const mockRedisClient = {
+ pipeline: mockPipeline,
+} as any;
+
+const appEnvMock = {
+ AGENT_GATEWAY_SERVICE_TOKEN: 'test-token',
+};
+
+vi.mock('@/envs/app', () => ({
+ get appEnv() {
+ return appEnvMock;
+ },
+}));
+
+let currentRedisClient: any = mockRedisClient;
+vi.mock('@/server/modules/AgentRuntime/redis', () => ({
+ getAgentRuntimeRedisClient: () => currentRedisClient,
+}));
+
+function buildRequest(body: unknown, token?: string) {
+ const headers = new Headers({ 'content-type': 'application/json' });
+ if (token) headers.set('authorization', `Bearer ${token}`);
+ return new NextRequest('https://test.com/api/agent/tool-result', {
+ body: JSON.stringify(body),
+ headers,
+ method: 'POST',
+ });
+}
+
+const validBody = {
+ content: '{"ok":true}',
+ success: true,
+ toolCallId: 'call-abc',
+};
+
+describe('/api/agent/tool-result POST', () => {
+ beforeEach(() => {
+ currentRedisClient = mockRedisClient;
+ appEnvMock.AGENT_GATEWAY_SERVICE_TOKEN = 'test-token';
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('returns 503 when AGENT_GATEWAY_SERVICE_TOKEN is not configured', async () => {
+ appEnvMock.AGENT_GATEWAY_SERVICE_TOKEN = '';
+ const response = await POST(buildRequest(validBody, 'test-token'));
+ expect(response.status).toBe(503);
+ });
+
+ it('returns 401 when authorization header is missing or wrong', async () => {
+ const response = await POST(buildRequest(validBody));
+ expect(response.status).toBe(401);
+
+ const response2 = await POST(buildRequest(validBody, 'wrong-token'));
+ expect(response2.status).toBe(401);
+ });
+
+ it('returns 400 when body is invalid', async () => {
+ const response = await POST(buildRequest({ toolCallId: 'x' }, 'test-token'));
+ expect(response.status).toBe(400);
+ });
+
+ it('returns 503 when Redis is unavailable', async () => {
+ currentRedisClient = null;
+ const response = await POST(buildRequest(validBody, 'test-token'));
+ expect(response.status).toBe(503);
+ });
+
+ it('LPUSHes the payload and sets TTL on happy path', async () => {
+ const response = await POST(buildRequest(validBody, 'test-token'));
+ expect(response.status).toBe(204);
+ expect(mockLpush).toHaveBeenCalledWith(
+ 'tool_result:call-abc',
+ expect.stringContaining('"toolCallId":"call-abc"'),
+ );
+ expect(mockExpire).toHaveBeenCalledWith('tool_result:call-abc', 120);
+ expect(mockPipelineExec).toHaveBeenCalled();
+ });
+
+ it('returns 503 when Redis pipeline exec throws', async () => {
+ mockPipelineExec.mockRejectedValueOnce(new Error('redis down'));
+ const response = await POST(buildRequest(validBody, 'test-token'));
+ expect(response.status).toBe(503);
+ });
+});
diff --git a/src/app/(backend)/api/agent/tool-result/route.ts b/src/app/(backend)/api/agent/tool-result/route.ts
new file mode 100644
index 00000000000..05b681bd1da
--- /dev/null
+++ b/src/app/(backend)/api/agent/tool-result/route.ts
@@ -0,0 +1,83 @@
+import debug from 'debug';
+import { type NextRequest, NextResponse } from 'next/server';
+import { z } from 'zod';
+
+import { appEnv } from '@/envs/app';
+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
+
+const log = debug('api-route:agent:tool-result');
+
+const TOOL_RESULT_TTL_SECONDS = 120;
+
+const ToolResultBodySchema = z.object({
+ content: z.string().nullable(),
+ error: z
+ .object({
+ message: z.string(),
+ type: z.string().optional(),
+ })
+ .optional(),
+ success: z.boolean(),
+ toolCallId: z.string().min(1),
+});
+
+/**
+ * Receive a tool execution result from Agent Gateway, originating from a
+ * client that executed a server-dispatched tool_execute. The result is
+ * LPUSH'd into a per-toolCallId list so the server-side agent loop's BLPOP
+ * can wake up and continue.
+ *
+ * Authenticated with AGENT_GATEWAY_SERVICE_TOKEN (the Gateway is the only
+ * trusted caller). Idempotency is not required: BLPOP will pop the first
+ * available value; duplicates sit under TTL until they expire.
+ */
+export async function POST(request: NextRequest) {
+ const serviceToken = appEnv.AGENT_GATEWAY_SERVICE_TOKEN;
+ if (!serviceToken) {
+ log('AGENT_GATEWAY_SERVICE_TOKEN is not configured');
+ return NextResponse.json({ error: 'Service not configured' }, { status: 503 });
+ }
+
+ const authHeader = request.headers.get('authorization');
+ if (authHeader !== `Bearer ${serviceToken}`) {
+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
+ }
+
+ let parsed;
+ try {
+ const body = await request.json();
+ parsed = ToolResultBodySchema.safeParse(body);
+ } catch {
+ return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
+ }
+
+ if (!parsed.success) {
+ return NextResponse.json(
+ { error: 'Invalid body', issues: parsed.error.issues },
+ { status: 400 },
+ );
+ }
+
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) {
+ log('Redis is not available');
+ return NextResponse.json({ error: 'Redis unavailable' }, { status: 503 });
+ }
+
+ const { toolCallId } = parsed.data;
+ const key = `tool_result:${toolCallId}`;
+
+ try {
+ await redis
+ .pipeline()
+ .lpush(key, JSON.stringify(parsed.data))
+ .expire(key, TOOL_RESULT_TTL_SECONDS)
+ .exec();
+ log('Persisted tool result for %s (success=%s)', toolCallId, parsed.data.success);
+ } catch (error) {
+ log('Failed to LPUSH tool result for %s: %O', toolCallId, error);
+ return NextResponse.json({ error: 'Redis write failed' }, { status: 503 });
+ }
+
+ return new NextResponse(null, { status: 204 });
+}