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

serve.ts

213 lines7.4 KB

1import { createServer } from 'node:http'
2import { Readable } from 'node:stream'
3import { pipeline } from 'node:stream/promises'
4import { randomBytes, timingSafeEqual } from 'node:crypto'
5import { createHarnessHandler } from '@tanstack/ai-harness/server'
6import { loadOptional } from './optional'
7import type { IncomingMessage, ServerResponse } from 'node:http'
8import type { ReadableStream as NodeReadableStream } from 'node:stream/web'
9import type { AnyHarness, HarnessHost, HarnessUser } from '@tanstack/ai-harness'
10import type { McpHarnessModule } from './optional'
11​
12export interface ServeOptions<U extends HarnessUser = HarnessUser> {
13 /**
14 * The host. With `access`, `access.getUser` reads the user of each
15 * request that has the token.
16 */
17 host: HarnessHost<U>
18 harness: AnyHarness
19 port: number
20 hostname: string
21 /**
22 * Every request must send `Authorization: Bearer <token>`. Only a signed
23 * media URL needs no token. On a host with access, the handler still reads
24 * its user with `getUser`.
25 */
26 token: string
27 /**
28 * The key that signs media URLs, at least 32 bytes (UTF-8). Default: a new
29 * random key at each start, so a signed URL stops working after a restart.
30 * It is never made from `token`: a signed URL is given out without the
31 * token, and must not let anyone guess it.
32 */
33 mediaKey?: string
34 /** The conversation of an MCP tool call that names none. Default `'main'`. */
35 threadId?: string
36 /** How `/mcp` handles tool calls that need approval. Default `'ask'`. */
37 approvals?: 'ask' | 'auto'
38 /**
39 * On a host without access: who a request with the token is. Without it,
40 * each request runs with no user (one user).
41 */
42 user?: U
44​
45/**
46 * The MCP server for `/mcp`, or `undefined` without `@tanstack/ai-mcp`. It
47 * runs each call as the same user as the session protocol routes.
48 */
49async function mcpServer<U extends HarnessUser>(
50 options: ServeOptions<U>,
51 withAccess: boolean,
52) {
53 const mcp = await loadOptional<McpHarnessModule>(
54 '@tanstack/ai-mcp/harness',
55 'createHarnessMcpServer',
56 )
57 if (mcp === undefined) return undefined
58 const { host, harness, user } = options
59 const shared = {
60 host,
61 harness,
62 threadId: options.threadId,
63 approvals: options.approvals,
64 }
65 // On a host with access, `getUser` reads the user of each request.
66 if (withAccess) return mcp.createHarnessMcpServer(shared)
67 return mcp.createHarnessMcpServer({
68 ...shared,
69 openAccess: user ? { user } : true,
70 })
72​
73/** A signed media URL needs no token: the handler checks its signature. */
74function isSignedMedia(request: Request) {
75 const url = new URL(request.url)
76 return (
77 request.method === 'GET' &&
78 url.pathname.split('/').at(-1) === 'media' &&
79 url.searchParams.has('sig')
80 )
82​
83/** A random token for `--serve` when none is given. */
84export function createToken(): string {
85 return randomBytes(24).toString('base64url')
87​
88function sameToken(given: string | null, expected: string): boolean {
89 if (!given?.startsWith('Bearer ')) return false
90 const a = Buffer.from(given.slice(7))
91 const b = Buffer.from(expected)
92 return a.length === b.length && timingSafeEqual(a, b)
94​
95async function toRequest(
96 req: IncomingMessage,
97 base: string,
98 signal: AbortSignal,
99): Promise<Request> {
100 const headers = new Headers()
101 for (const [key, value] of Object.entries(req.headers)) {
102 if (typeof value === 'string') headers.set(key, value)
103 else if (Array.isArray(value)) headers.set(key, value.join(', '))
104 }
105 const hasBody = req.method !== 'GET' && req.method !== 'HEAD'
106 const chunks: Array<Buffer> = []
107 if (hasBody) for await (const chunk of req) chunks.push(Buffer.from(chunk))
108 return new Request(new URL(req.url ?? '/', base), {
109 method: req.method ?? 'GET',
110 headers,
111 signal,
112 ...(hasBody ? { body: Buffer.concat(chunks) } : {}),
113 })
115​
116async function send(res: ServerResponse, response: Response): Promise<void> {
117 res.writeHead(response.status, Object.fromEntries(response.headers))
118 if (!response.body) {
119 res.end()
120 return
121 }
122 // `Readable.fromWeb` takes the stream type from node:stream/web. When the
123 // body fails, for example after the client left, `pipeline` ends `res`.
124 await pipeline(
125 Readable.fromWeb(response.body as NodeReadableStream),
126 res,
127 ).catch(() => {})
129​
130/**
131 * Serve the harness session protocol over HTTP (capabilities, run, events,
132 * control, snapshot). With `@tanstack/ai-mcp` installed, `/mcp` serves the
133 * harness as an MCP server. Every request needs the bearer token, except a
134 * signed media URL. Then on a host with access, `getUser` reads the user of
135 * the request, and the host checks each action. Without access, each
136 * request runs as `user`.
137 */
138export async function serve<U extends HarnessUser = HarnessUser>(
139 options: ServeOptions<U>,
140): Promise<{ url: string; close: () => Promise<void> }> {
141 const { host, harness, user } = options
142 const isAllowed = (request: Request) =>
143 sameToken(request.headers.get('authorization'), options.token)
144 const withAccess = host.hasAccess
145 // Without `mediaKey`, the handler signs with a new random key, so signed
146 // media URLs stop working after a restart.
147 const media =
148 options.mediaKey !== undefined
149 ? { media: { secret: options.mediaKey } }
150 : {}
151 const handler = withAccess
152 ? createHarnessHandler({ host, harness, ...media })
153 : createHarnessHandler({
154 host,
155 harness,
156 // One user holds the token, so it can use every thread.
157 openAccess: user ? { user } : true,
158 ...media,
159 })
160 const mcp = await mcpServer(options, withAccess)
161 const route = (request: Request) => {
162 if (!isAllowed(request) && !isSignedMedia(request)) {
163 return Response.json({ error: 'unauthorized' }, { status: 401 })
164 }
165 const isMcp = mcp !== undefined && new URL(request.url).pathname === '/mcp'
166 return isMcp ? mcp.fetch(request) : handler(request)
167 }
168 const server = createServer((req, res) => {
169 const aborter = new AbortController()
170 res.on('close', () => aborter.abort())
171 // Refuse a body without the token before reading it. Signed media URLs
172 // carry no token, but they are GET requests.
173 const hasBody = req.method !== 'GET' && req.method !== 'HEAD'
174 if (
175 hasBody &&
176 !sameToken(req.headers.authorization ?? null, options.token)
177 ) {
178 res.writeHead(401, { 'Content-Type': 'application/json' })
179 res.end(JSON.stringify({ error: 'unauthorized' }))
180 return
181 }
182 void (async () => {
183 try {
184 const base = `http://${req.headers.host ?? `${options.hostname}:${options.port}`}`
185 await send(res, await route(await toRequest(req, base, aborter.signal)))
186 } catch (error) {
187 if (!res.headersSent)
188 res.writeHead(500, { 'Content-Type': 'application/json' })
189 res.end(
190 JSON.stringify({
191 error: error instanceof Error ? error.message : String(error),
192 }),
193 )
194 }
195 })()
196 })
197 return new Promise((resolve, reject) => {
198 server.once('error', reject)
199 server.listen(options.port, options.hostname, () => {
200 const address = server.address()
201 const port =
202 typeof address === 'object' && address ? address.port : options.port
203 resolve({
204 url: `http://${options.hostname}:${port}`,
205 close: () =>
206 new Promise<void>((done) => {
207 server.closeAllConnections()
208 server.close(() => done())
209 }),
210 })
211 })
212 })