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

mcp-lifecycle.spec.ts

80 lines2.3 KB

1import { test, expect } from './fixtures'
2​
3/**
4 * `chat({ mcp: { connection } })` lifecycle semantics, end-to-end.
5 *
6 * `api.mcp-lifecycle-test` runs a real chat() agent loop with one MCP client,
7 * drains it, then probes whether the client is still usable:
8 * - 'close' (default) → chat closed it → not usable.
9 * - 'keep-alive' → chat left it open → still usable.
10 *
11 * The unit tests assert this against fake sources; this proves it against a
12 * real `createMCPClient` over Streamable HTTP. aimock returns a plain text turn
13 * (fixtures/mcp/lifecycle.json) — no tool call needed; only lifecycle matters.
14 */
15async function runLifecycle(
16 request: import('@playwright/test').APIRequestContext,
17 opts: {
18 testId: string
19 aimockPort: number
20 connection: 'close' | 'keep-alive'
21 },
22) {
23 const res = await request.post('/api/mcp-lifecycle-test', {
24 headers: { 'Content-Type': 'application/json' },
25 data: {
26 threadId: `mcp-life-${opts.testId}`,
27 runId: `mcp-life-run-${opts.testId}`,
28 state: {},
29 messages: [
30 { id: 'mcp-life-msg-1', role: 'user', content: '[mcp-lifecycle] ping' },
31 ],
32 tools: [],
33 context: [],
34 forwardedProps: {
35 testId: opts.testId,
36 aimockPort: opts.aimockPort,
37 connection: opts.connection,
38 },
39 },
40 })
41 const body = await res.text()
42 expect(
43 res.ok(),
44 `mcp-lifecycle-test (${opts.connection}) failed (${res.status()}): ${body}`,
45 ).toBe(true)
46 return JSON.parse(body) as {
47 connection: string
48 survivedAfterRun: boolean
49 }
51​
52test.describe('mcp — chat({ mcp }) connection lifecycle', () => {
53 test("connection: 'close' (default) closes the client after the run", async ({
54 request,
55 testId,
56 aimockPort,
57 }) => {
58 const json = await runLifecycle(request, {
59 testId: `${testId}-close`,
60 aimockPort,
61 connection: 'close',
62 })
63 expect(json.connection).toBe('close')
64 expect(json.survivedAfterRun).toBe(false)
65 })
66​
67 test("connection: 'keep-alive' leaves the client open after the run", async ({
68 request,
69 testId,
70 aimockPort,
71 }) => {
72 const json = await runLifecycle(request, {
73 testId: `${testId}-keepalive`,
74 aimockPort,
75 connection: 'keep-alive',
76 })
77 expect(json.connection).toBe('keep-alive')
78 expect(json.survivedAfterRun).toBe(true)
79 })
80})