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

session-store.ts

116 lines4.4 KB

1import type { ClientOptions } from '@modelcontextprotocol/client'
2import type { TransportConfig } from '../transport'
3import type { MCPClientOptions } from '../types'
4​
5export interface McpServerDescriptor {
6 /**
7 * The serializable connection config the call handler reconnects from.
8 * `undefined` for a client built from a ready-made `Transport` instance
9 * (single-use, not reconnectable) — the handler rejects such a call with a
10 * clear error.
11 */
12 transport: TransportConfig | undefined
13 prefix?: string
14 /**
15 * Options to rebuild the client with. Carried so a reconnect keeps a custom
16 * `jsonSchemaValidator` — an edge runtime cannot use the SDK's AJV default.
17 */
18 clientOptions?: ClientOptions
19 /** Carried so a reconnect hides the same tools from widgets as from the model. */
20 toolFilter?: MCPClientOptions['toolFilter']
21 /** Carried so a widget cannot run a tool that the model can run only after approval. */
22 needsApproval?: MCPClientOptions['needsApproval']
23 /** Carried so a reconnect names the tools the same way as for the model. */
24 toolName?: MCPClientOptions['toolName']
25 /** Carried so a widget call waits as long as a model tool call. */
26 requestOptions?: MCPClientOptions['requestOptions']
28​
29export interface McpSessionStore {
30 /**
31 * Resolve the server descriptor for a thread+serverId, or null if unknown.
32 *
33 * `serverId` may be undefined when the widget omits it (single-server setups);
34 * implementations should default to the sole recorded server in that case.
35 */
36 get: (
37 threadId: string,
38 serverId: string | undefined,
39 ) => Promise<McpServerDescriptor | null>
40 /** Record the servers a thread may interact with (called from the chat route). */
41 set: (
42 threadId: string,
43 servers: Record<string, McpServerDescriptor>,
44 ) => Promise<void>
46​
47/** Call-handler request shape; imported by call-handler.ts from this module. */
48export interface McpAppCallRequest {
49 threadId: string
50 /**
51 * The server the widget targets. May be undefined when the widget omits it
52 * (single-server setups) — the handler defaults to the sole configured server.
53 */
54 serverId?: string
55 toolName: string
56 args?: unknown
57 /**
58 * Reserved — forwarded by the bridge for correlation purposes but not
59 * consumed by the call handler. Mirrors the `meta` convention: accepted
60 * on the wire, carried through, but the handler does not read it.
61 */
62 messageId?: string
64​
65/**
66 * Creates a simple in-memory McpSessionStore.
67 *
68 * TTL is enforced on read (prune-on-read) and slides on each successful hit —
69 * this is single-instance only. The `McpSessionStore` interface is the
70 * extension point for persistent/SQL backends, which can drop in later with no
71 * API change.
72 *
73 * Growth is bounded by an opportunistic sweep on `set()`: prune-on-read alone
74 * never reclaims a thread that is recorded but never has a widget interaction
75 * (the common case — most threads never touch a `ui://` widget), so without the
76 * sweep the map would grow by one entry per chat thread for the process
77 * lifetime. The sweep drops every entry older than the TTL whenever a new one is
78 * written, keeping the map bounded to threads active within the TTL window.
79 */
80export function inMemoryMcpSessionStore(
81 opts: { ttlMs?: number } = {},
82): McpSessionStore {
83 const map = new Map<
84 string,
85 { at: number; servers: Record<string, McpServerDescriptor> }
86 >()
87 const ttl = opts.ttlMs ?? 30 * 60_000
88​
89 return {
90 async set(threadId, servers) {
91 // Opportunistic sweep: reclaim every expired entry, not just this thread,
92 // so set-but-never-read threads can't accumulate unbounded.
93 const now = Date.now()
94 for (const [id, e] of map) {
95 if (now - e.at > ttl) map.delete(id)
96 }
97 map.set(threadId, { at: now, servers })
98 },
99 async get(threadId, serverId) {
100 const e = map.get(threadId)
101 if (!e || Date.now() - e.at > ttl) {
102 map.delete(threadId)
103 return null
104 }
105 // Sliding TTL: refresh on a successful hit so an actively-used thread
106 // doesn't expire by absolute time mid-session.
107 e.at = Date.now()
108 // serverId omitted (single-server setups): default to the sole server.
109 if (serverId === undefined) {
110 const entries = Object.entries(e.servers)
111 return entries.length === 1 ? (entries[0]?.[1] ?? null) : null
112 }
113 return e.servers[serverId] ?? null
114 },
115 }