@anthropic-ai/sdk TypeScript: inspect the JSON request body a custom fetch receives for a tool_result follow-up messages.create call
In @anthropic-ai/sdk 1.8.0 on Node v22.23.3, the custom fetch passed to new Anthropic({ apiKey: 'sk-ant-dummy', fetch: myFetch }) received init.body as a JSON string, and JSON.parse(init.body) on the second messages.create call (assistant content: m1.content, then a user tool_result block) gave: {"model":"claude-sonnet-4-5","max_tokens":100,"tools":[{"name":"get_weather","description":"w","input_schema":{"type":"object","properties":{"city":{"type":"string"}}}}],"messages":[{"role":"user","content":"weather?"},{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"get_weather","input":{"city":"Paris"}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"sunny"}]}]}. Script run with env -u ANTHROPIC_API_KEY node b.mjs:
import Anthropic from '@anthropic-ai/sdk'; const bodies = []; const myFetch = async (url, init) => { bodies.push(JSON.parse(init.body)); const n = bodies.length; const out = n === 1 ? { id:'msg_1', type:'message', role:'assistant', model:'claude-sonnet-4-5', content:[{type:'tool_use', id:'toolu_1', name:'get_weather', input:{city:'Paris'}}], stop_reason:'tool_use', stop_sequence:null, usage:{input_tokens:1, output_tokens:1} } : { id:'msg_2', type:'message', role:'assistant', model:'claude-sonnet-4-5', content:[{type:'text', text:'Sunny'}], stop_reason:'end_turn', stop_sequence:null, usage:{input_tokens:1, output_tokens:1} }; return new Response(JSON.stringify(out), { status:200, headers:{'content-type':'application/json'} }); }; const client = new Anthropic({ apiKey:'sk-ant-dummy', fetch: myFetch }); const tools = [{name:'get_weather', description:'w', input_schema:{type:'object', properties:{city:{type:'string'}}}}]; const m1 = await client.messages.create({model:'claude-sonnet-4-5', max_tokens:100, tools, messages:[{role:'user', content:'weather?'}]}); console.log('content[0]:', JSON.stringify(m1.content[0])); console.log('stop_reason:', m1.stop_reason); const m2 = await client.messages.create({model:'claude-sonnet-4-5', max_tokens:100, tools, messages:[ {role:'user', content:'weather?'}, {role:'assistant', content:m1.content}, {role:'user', content:[{type:'tool_result', tool_use_id:'toolu_1', content:'sunny'}]}]}); console.log('second body:', JSON.stringify(bodies[1])); console.log('m2:', m2.stop_reason, JSON.stringify(m2.content[0]));