Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

tool-choice.test.ts

162 lines5.6 KB

1/**
2 * `chat({ toolChoice })` on the Claude Code adapter. A fake `claude` CLI
3 * writes its argv to a file, and a fake bridge provisioner records which
4 * chat() tools reach the bridge.
5 */
6import { afterAll, describe, expect, it, vi } from 'vitest'
7import * as fsp from 'node:fs/promises'
8import * as os from 'node:os'
9import * as path from 'node:path'
10import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
11import {
12 provideSandbox,
13 provideToolBridgeProvisioner,
14} from '@tanstack/ai-sandbox'
15import { resolveDebugOption } from '@tanstack/ai/adapter-internals'
16import { claudeCodeText } from '../src/index'
17import type { AnyTool, CapabilityContext, ToolChoice } from '@tanstack/ai'
18​
19const baseDir = path.join(os.tmpdir(), `tanstack-ai-cc-choice-${Date.now()}`)
20const provider = localProcessSandbox({ baseDir, removeOnDestroy: true })
21​
22afterAll(async () => {
23 await fsp.rm(baseDir, { recursive: true, force: true })
24})
25​
26const FAKE_CLAUDE = [
27 `import { writeFileSync } from 'node:fs'`,
28 `writeFileSync('argv.json', JSON.stringify(process.argv.slice(2)))`,
29 `process.stdin.resume()`,
30 `process.stdin.on('end', () => {`,
31 ` const w = (o) => process.stdout.write(JSON.stringify(o) + '\\n')`,
32 ` w({ type: 'system', subtype: 'init', session_id: 's', model: 'haiku', tools: [] })`,
33 ` w({ type: 'result', subtype: 'success', result: 'ok', usage: { input_tokens: 1, output_tokens: 1 } })`,
34 `})`,
35].join('\n')
36​
37const tools: Array<AnyTool> = [
38 { name: 'getWeather', description: 'weather' },
39 { name: 'getTime', description: 'time' },
41​
42async function collect<T>(stream: AsyncIterable<T>): Promise<Array<T>> {
43 const out: Array<T> = []
44 for await (const chunk of stream) out.push(chunk)
45 return out
47​
48function loggerWith(warn: (message: string) => void) {
49 return resolveDebugOption({
50 logger: { debug: () => {}, info: () => {}, warn, error: () => {} },
51 })
53​
54/** Run the adapter once in a real sandbox. Returns the argv and bridged tools. */
55async function run(toolChoice: ToolChoice) {
56 const sbx = await provider.create({})
57 try {
58 await sbx.fs.write('/workspace/fake-claude.mjs', FAKE_CLAUDE)
59 const bridged: Array<Array<string>> = []
60 const capabilities = {
61 capabilities: { markProvided: () => {}, has: () => true },
62 } as unknown as CapabilityContext
63 provideSandbox(capabilities, sbx)
64 provideToolBridgeProvisioner(capabilities, {
65 provision: (provisioned) => {
66 bridged.push(provisioned.map((tool) => tool.name))
67 return Promise.resolve({
68 name: 'tanstack',
69 url: 'http://127.0.0.1:1/mcp',
70 token: 'token',
71 close: () => Promise.resolve(),
72 })
73 },
74 })
75 const adapter = claudeCodeText('haiku', {
76 claudeExecutable: 'node fake-claude.mjs',
77 streamPartials: false,
78 emitDiff: false,
79 })
80 const chunks = await collect(
81 adapter.chatStream({
82 threadId: 'thread-1',
83 model: 'haiku',
84 messages: [{ role: 'user', content: 'hi' }],
85 logger: loggerWith(() => {}),
86 capabilities,
87 tools,
88 toolChoice,
89 }),
90 )
91 expect(chunks.find((chunk) => chunk.type === 'RUN_ERROR')).toBeUndefined()
92 const argv: unknown = JSON.parse(await sbx.fs.read('/workspace/argv.json'))
93 return { argv, bridged }
94 } finally {
95 await sbx.destroy()
96 }
98​
99describe('claude-code toolChoice', () => {
100 it("'none' bridges no chat() tool and turns off every other tool", async () => {
101 const { argv, bridged } = await run('none')
102 expect(bridged).toEqual([])
103 expect(argv).toEqual(
104 expect.arrayContaining(['--tools', '', '--strict-mcp-config']),
105 )
106 })
107​
108 it('a named tool bridges only that tool and turns off the others', async () => {
109 const { argv, bridged } = await run({ type: 'tool', name: 'getTime' })
110 expect(bridged).toEqual([['getTime']])
111 expect(argv).toEqual(
112 expect.arrayContaining(['--tools', '', '--strict-mcp-config']),
113 )
114 })
115​
116 it("'auto' bridges every chat() tool and keeps the built-in tools", async () => {
117 const { argv, bridged } = await run('auto')
118 expect(bridged).toEqual([['getWeather', 'getTime']])
119 expect(argv).not.toContain('--tools')
120 expect(argv).not.toContain('--strict-mcp-config')
121 })
122​
123 // The warning comes before the sandbox lookup, so these calls need no
124 // sandbox. They end with a RUN_ERROR for the missing sandbox.
125 async function callWithoutSandbox(
126 adapter: ReturnType<typeof claudeCodeText>,
127 warn: (message: string) => void,
128 toolChoice: ToolChoice | undefined,
129 ) {
130 await collect(
131 adapter.chatStream({
132 threadId: 'thread-1',
133 model: 'haiku',
134 messages: [{ role: 'user', content: 'hi' }],
135 logger: loggerWith(warn),
136 tools,
137 ...(toolChoice !== undefined && { toolChoice }),
138 }),
139 )
140 }
141​
142 it("'required' warns once per adapter instance", async () => {
143 const warn = vi.fn()
144 const adapter = claudeCodeText('haiku')
145 await callWithoutSandbox(adapter, warn, 'required')
146 await callWithoutSandbox(adapter, warn, 'required')
147 expect(warn).toHaveBeenCalledTimes(1)
148 expect(warn.mock.calls[0]?.[0]).toContain(
149 "claude-code: toolChoice 'required' is not supported",
150 )
151 })
152​
153 it("'auto', unset, 'none', and a named tool do not warn", async () => {
154 const warn = vi.fn()
155 const adapter = claudeCodeText('haiku')
156 await callWithoutSandbox(adapter, warn, 'auto')
157 await callWithoutSandbox(adapter, warn, undefined)
158 await callWithoutSandbox(adapter, warn, 'none')
159 await callWithoutSandbox(adapter, warn, { type: 'tool', name: 'getTime' })
160 expect(warn).not.toHaveBeenCalled()
161 })
162})