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

api.mcp-policy-test.ts

56 lines1.8 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 maxIterations,
6 toServerSentEventsResponse,
7} from '@tanstack/ai'
8import { createMCPClient } from '@tanstack/ai-mcp'
9import { createTextAdapter } from '@/lib/providers'
10​
11/** `chat({ mcp })` with the client tool policy named by `forwardedProps.policy`. */
12export const Route = createFileRoute('/api/mcp-policy-test')({
13 server: {
14 handlers: {
15 POST: async ({ request }) => {
16 let params
17 try {
18 params = await chatParamsFromRequestBody(await request.json())
19 } catch (error) {
20 return new Response(
21 error instanceof Error ? error.message : 'Bad request',
22 { status: 400 },
23 )
24 }
25​
26 const fp = params.forwardedProps
27 const testId = typeof fp.testId === 'string' ? fp.testId : undefined
28 const aimockPort =
29 fp.aimockPort != null ? Number(fp.aimockPort) : undefined
30 const policy = typeof fp.policy === 'string' ? fp.policy : 'none'
31​
32 const origin = new URL(request.url).origin
33 const client = await createMCPClient({
34 transport: { type: 'http', url: `${origin}/api/mcp-server` },
35 ...(policy === 'readOnly'
36 ? {
37 toolFilter: (tool) => tool.annotations?.readOnlyHint === true,
38 }
39 : {}),
40 ...(policy === 'approval' ? { needsApproval: () => true } : {}),
41 })
42​
43 const stream = chat({
44 ...createTextAdapter('openai', undefined, aimockPort, testId),
45 messages: params.messages,
46 threadId: params.threadId,
47 runId: params.runId,
48 mcp: { clients: [client] },
49 agentLoopStrategy: maxIterations(5),
50 })
51​
52 return toServerSentEventsResponse(stream)
53 },
54 },
55 },
56})