Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 createChatOptions,
5 maxIterations,
6 toolDefinition,
7} from '@tanstack/ai'
8import { createAnthropicChat } from '@tanstack/ai-anthropic'
9import { webFetchTool } from '@tanstack/ai-anthropic/tools'
10import { z } from 'zod'
11import type { UIMessage } from '@tanstack/ai'
12
13const LLMOCK_DEFAULT_BASE = process.env.LLMOCK_URL || 'http://127.0.0.1:4010'
14const DUMMY_KEY = 'sk-e2e-test-dummy-key'
15
16/**
17 * Reproduces issue #604 against the real `webFetchTool()` surface: a user
18 * client tool mixed with `webFetchTool()` previously broke when Claude
19 * returned a `tool_use` followed by a `server_tool_use` (web_fetch) in the
20 * same streaming response — the server tool's `input_json_delta`s appended
21 * onto the client tool's input buffer, and the agent loop's `JSON.parse`
22 * threw on the concatenated JSON.
23 *
24 * The route runs the Anthropic adapter against a mounted aimock path that
25 * emits the exact SSE shape Claude returns (aimock doesn't natively model
26 * `server_tool_use` blocks). Test-only — no production code path should set
27 * a custom Anthropic baseURL like this.
28 */
29export const Route = createFileRoute('/api/anthropic-bug-test')({
30 server: {
31 handlers: {
32 POST: async ({ request }) => {
33 const adapter = createAnthropicChat('claude-sonnet-4-5', DUMMY_KEY, {
34 baseURL: `${LLMOCK_DEFAULT_BASE}/anthropic-bug-test`,
35 })
36
37 if (
38 new URL(request.url).searchParams.get('case') === 'thinking-order'
39 ) {
40 const messages: Array<UIMessage> = [
41 {
42 id: 'initial-user-message',
43 role: 'user',
44 parts: [{ type: 'text', content: 'Research top AI companies' }],
45 },
46 {
47 id: 'assistant-message',
48 role: 'assistant',
49 parts: [
50 {
51 type: 'thinking',
52 content: 'First signed thinking block',
53 signature: 'signature-1',
54 },
55 {
56 type: 'tool-call',
57 id: 'srvtoolu_search',
58 name: 'web_search',
59 arguments: '{"query":"top AI companies"}',
60 state: 'input-complete',
61 metadata: {
62 providerExecuted: true,
63 anthropic: {
64 serverToolType: 'web_search',
65 resultBlockType: 'web_search_tool_result',
66 result: [
67 {
68 type: 'web_search_result',
69 title: 'Example result',
70 url: 'https://example.com',
71 encrypted_content: 'opaque-provider-payload',
72 },
73 ],
74 },
75 },
76 },
77 {
78 type: 'thinking',
79 content: 'Second signed thinking block',
80 signature: 'signature-2',
81 },
82 {
83 type: 'tool-call',
84 id: 'toolu_create_block',
85 name: 'createBlock',
86 arguments: '{"block":{"type":"entity-grid"}}',
87 state: 'complete',
88 output: { ok: true },
89 },
90 {
91 type: 'tool-result',
92 toolCallId: 'toolu_create_block',
93 content: '{"ok":true}',
94 state: 'complete',
95 },
96 ],
97 },
98 {
99 id: 'follow-up-user-message',
100 role: 'user',
101 parts: [
102 {
103 type: 'text',
104 content: '[thinking-tool-order] continue',
105 },
106 ],
107 },
108 ]
109
110 const chunks: Array<unknown> = []
111 try {
112 for await (const chunk of chat({
113 threadId: 'anthropic-bug-test',
114 ...createChatOptions({ adapter }),
115 messages,
116 })) {
117 chunks.push(chunk)
118 }
119 } catch (error) {
120 return new Response(
121 JSON.stringify({
122 chunks,
123 error: error instanceof Error ? error.message : String(error),
124 }),
125 { status: 200, headers: { 'Content-Type': 'application/json' } },
126 )
127 }
128
129 return new Response(JSON.stringify({ chunks, error: null }), {
130 status: 200,
131 headers: { 'Content-Type': 'application/json' },
132 })
133 }
134
135 // A trivial client tool the user might pair with webFetchTool(). The
136 // server lookup just echoes back so the agent loop can settle into
137 // the follow-up text response.
138 const lookupWeather = toolDefinition({
139 name: 'lookup_weather',
140 description: 'Return the current weather for a city',
141 inputSchema: z.object({ location: z.string() }),
142 }).server(async ({ location }) => ({ location, summary: 'sunny' }))
143
144 const chunks: Array<unknown> = []
145 try {
146 for await (const chunk of chat({
147 threadId: 'anthropic-bug-test',
148 ...createChatOptions({ adapter }),
149 // The real bug surface: a user tool + webFetchTool() in the same
150 // request. Pre-fix this combination caused
151 // "Failed to parse tool arguments as JSON" in the agent loop.
152 tools: [lookupWeather, webFetchTool()],
153 messages: [
154 {
155 role: 'user',
156 content: 'Weather in Berlin and fetch example.com',
157 },
158 ],
159 agentLoopStrategy: maxIterations(3),
160 })) {
161 chunks.push(chunk)
162 }
163 } catch (error) {
164 return new Response(
165 JSON.stringify({
166 chunks,
167 error: error instanceof Error ? error.message : String(error),
168 }),
169 { status: 200, headers: { 'Content-Type': 'application/json' } },
170 )
171 }
172
173 return new Response(JSON.stringify({ chunks, error: null }), {
174 status: 200,
175 headers: { 'Content-Type': 'application/json' },
176 })
177 },
178 },
179 },
180})