feat(ai-mcp): add attachResources, prompts, maxTools, and OAuth redirect helpers #2241
OpenJeffSouop(GitHub profile, opens in a new tab)wants to merge 10 commits into
main fromrefs/pull/2241/headopened View on GitHubtanstack-source added labelsfeature
- @@ -0,0 +16,21 @@16+You need [MCP Client Input](../../tools/mcp-input) on the server route first (`parentRunId` + `resume`).17+18+## Full example (React)19+20+```tsx21+import { useState } from 'react'22+import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'23+24+function isRecord(value: unknown): value is Record<string, unknown> {25+ return typeof value === 'object' && value !== null && !Array.isArray(value)26+}27+28+function readMcpForm(metadata: Readonly<Record<string, unknown>> | undefined) {29+ const payload = metadata?.['tanstack:interruptPayload']30+ if (!isRecord(payload) || payload.kind !== 'form') return undefined31+ if (!isRecord(payload.request)) return undefined32+ return payload.request33+}34+35+export function McpFormInterrupt() {36+ const [answer, setAnswer] = useState('')@@ -0,0 +20,21 @@20+```tsx21+import { useState } from 'react'22+import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'23+24+function isRecord(value: unknown): value is Record<string, unknown> {25+ return typeof value === 'object' && value !== null && !Array.isArray(value)26+}27+28+function readMcpForm(metadata: Readonly<Record<string, unknown>> | undefined) {29+ const payload = metadata?.['tanstack:interruptPayload']30+ if (!isRecord(payload) || payload.kind !== 'form') return undefined31+ if (!isRecord(payload.request)) return undefined32+ return payload.request33+}34+35+export function McpFormInterrupt() {36+ const [answer, setAnswer] = useState('')37+ const { interrupts } = useChat({38+ threadId: 'thread-1',39+ connection: fetchServerSentEvents('/api/chat'),40+ })@@ -0,0 +34,21 @@34+35+export function McpFormInterrupt() {36+ const [answer, setAnswer] = useState('')37+ const { interrupts } = useChat({38+ threadId: 'thread-1',39+ connection: fetchServerSentEvents('/api/chat'),40+ })41+42+ return (43+ <>44+ {interrupts.map((interrupt) => {45+ if (!interrupt.id.startsWith('mcp_input_')) return null46+ if (interrupt.kind !== 'generic') return null47+ const request = readMcpForm(interrupt.metadata)48+ if (!request) return null49+ return (50+ <form51+ key={interrupt.id}52+ onSubmit={(event) => {53+ event.preventDefault()54+ interrupt.resolveInterrupt({ value: answer })@@ -0,0 +184,21 @@184+ saveCodeVerifier: (value) => {185+ verifier = value186+ },187+ codeVerifier: () => verifier,188+ }189+}190+191+async function persistPending(192+ tokenStore: McpTokenStore,193+ provider: OAuthClientProvider,194+): Promise<void> {195+ if (!tokenStore.savePending) {196+ throw new Error(197+ 'tokenStore.savePending is required for the OAuth redirect flow across requests',198+ )199+ }200+ const verifier =201+ typeof provider.codeVerifier === 'function' ? provider.codeVerifier() : ''202+ const information = await provider.clientInformation?.()203+ await tokenStore.savePending({204+ codeVerifier: typeof verifier === 'string' ? verifier : await verifier,@@ -0,0 +221,21 @@221+ *222+ * - When tokens are already in `tokenStore`, returns `{ status: 'connected' }`.223+ * - Otherwise returns `{ status: 'redirect', authorizationUrl }` — send the224+ * user there, then call {@link finishMCPOAuthRedirect} with the `code`.225+ *226+ * For a redirect that spans HTTP requests, `tokenStore` must implement227+ * `loadPending` / `savePending` / `clearPending`.228+ */229+export async function createMCPClientWithOAuthRedirect(230+ options: CreateMCPClientWithOAuthRedirectOptions,231+): Promise<MCPClientWithOAuthResult> {232+ const saved = await options.tokenStore.load()233+ if (saved?.accessToken) {234+ const provider = await tokenStoreProvider(235+ {236+ redirectUri: options.callbackUrl,237+ clientName: options.clientName ?? 'TanStack AI',238+ scopes: options.scopes,239+ tokenStore: options.tokenStore,240+ },241+ {},@@ -0,0 +291,21 @@291+/**292+ * Finish an OAuth redirect: exchange `code`, save tokens, return a connected293+ * MCP client. Call this from your callback route.294+ */295+export async function finishMCPOAuthRedirect(296+ options: CreateMCPClientWithOAuthRedirectOptions & { code: string },297+): Promise<MCPClient> {298+ const provider = await tokenStoreProvider(299+ {300+ redirectUri: options.callbackUrl,301+ clientName: options.clientName ?? 'TanStack AI',302+ scopes: options.scopes,303+ tokenStore: options.tokenStore,304+ },305+ {},306+ )307+ const transport = new StreamableHTTPClientTransport(new URL(options.url), {308+ authProvider: provider,309+ fetch: options.fetch,310+ })311+ await transport.finishAuth(options.code)@@ -9,7 +57,15 @@57+ *58+ * Returns `null` only when `onReject: 'omit'`.59+ *60+ * Keep in sync with `@tanstack/ai`'s internal61+ * `activities/chat/mcp/resource-parts.ts` (used by `chat({ mcp })`).962 */10-export function mcpResourceToContentPart(content: {11- uri?: string12- text?: string13- blob?: string14- [key: string]: unknown15-}): ContentPart {63+export function mcpResourceToContentPart(64+ content: {65+ uri?: string66+ mimeType?: string67+ text?: string68+ blob?: string69+ [key: string]: unknown70+ },71+ options?: McpResourceToContentPartOptions,@@ -9,7 +58,15 @@58+ * Returns `null` only when `onReject: 'omit'`.59+ *60+ * Keep in sync with `@tanstack/ai`'s internal61+ * `activities/chat/mcp/resource-parts.ts` (used by `chat({ mcp })`).962 */10-export function mcpResourceToContentPart(content: {11- uri?: string12- text?: string13- blob?: string14- [key: string]: unknown15-}): ContentPart {63+export function mcpResourceToContentPart(64+ content: {65+ uri?: string66+ mimeType?: string67+ text?: string68+ blob?: string69+ [key: string]: unknown70+ },71+ options?: McpResourceToContentPartOptions,72+): ContentPart | null {@@ -19,2 +80,20 @@1980 if (typeof content.blob === 'string') {20- return { type: 'text', content: `[binary resource ${content.uri ?? ''}]` }81+ const mime =82+ typeof content.mimeType === 'string'83+ ? content.mimeType.toLowerCase()84+ : ''85+ if (decodedByteLength(content.blob) > maxBytes) {86+ return reject(content.uri, 'over maxBytes', onReject)87+ }88+ if (mime.startsWith('image/')) {89+ return mediaPart('image', content.blob, mime)90+ }91+ if (mime.startsWith('audio/')) {92+ return mediaPart('audio', content.blob, mime)93+ }94+ if (95+ mime === 'application/pdf' ||96+ mime === 'text/plain' ||97+ mime.startsWith('text/')98+ ) {99+ return mediaPart('document', content.blob, mime || 'application/pdf')@@ -6674,6 +6679,18 @@66746679 signal: AbortSignal | undefined,6675-) {6680+): Promise<void> {6681+ let mcpTools66766682 try {6677- return await mcpManager.discover(signal)6683+ mcpTools = await mcpManager.discover(signal)66786684 } catch (error) {6679- if (signal?.aborted) return []6685+ if (signal?.aborted) return6686+ throw error6687+ }6688+ if (mcpTools.length > 0) {6689+ ;(textOptions as { tools?: Array<any> }).tools = [6690+ ...(textOptions.tools ?? []),6691+ ...mcpTools,6692+ ]6693+ }6694+6695+ try {6696+ const context = await mcpManager.resolveContext(signal)@@ -6678,2 +6683,20 @@6683+ mcpTools = await mcpManager.discover(signal)66786684 } catch (error) {6679- if (signal?.aborted) return []6685+ if (signal?.aborted) return6686+ throw error6687+ }6688+ if (mcpTools.length > 0) {6689+ ;(textOptions as { tools?: Array<any> }).tools = [6690+ ...(textOptions.tools ?? []),6691+ ...mcpTools,6692+ ]6693+ }6694+6695+ try {6696+ const context = await mcpManager.resolveContext(signal)6697+ if (6698+ context.promptMessages.length > 0 ||6699+ context.contentParts.length > 06700+ ) {6701+ ;(textOptions as { messages?: Array<any> }).messages =6702+ mergeMcpContextIntoMessages(textOptions.messages ?? [], context)@@ -76,0 +128,21 @@128+ if (Array.isArray(prompts)) return [...prompts]129+ return [prompts]130+}131+132+async function readUriFromSources(133+ sources: ReadonlyArray<MCPToolSource>,134+ uri: string,135+ requestMeta: MCPRequestMeta | undefined,136+): Promise<McpResourceReadResult | undefined> {137+ const errors: Array<unknown> = []138+ for (const source of sources) {139+ if (!source.readResource) continue140+ try {141+ const meta = await requestMeta?.({142+ method: 'resources/read',143+ serverId: undefined,144+ uri,145+ })146+ return await source.readResource(uri, {147+ ...(meta && { meta }),148+ })
Pushed38679c3
- @@ -0,0 +132,21 @@132+ ...(typeof promptName === 'string'133+ ? {134+ prompts: {135+ name: promptName,136+ args:137+ typeof promptArgs === 'object' && promptArgs !== null138+ ? promptArgs139+ : undefined,140+ },141+ }142+ : {}),143+ },144+})145+```146+147+In the client, load the list and send `promptName` / `promptArgs` with the next chat request:148+149+```ts150+const prompts = await fetch('/api/mcp-prompts').then((r) => r.json())151+152+await fetch('/api/chat', {@@ -0,0 +139,21 @@139+ : undefined,140+ },141+ }142+ : {}),143+ },144+})145+```146+147+In the client, load the list and send `promptName` / `promptArgs` with the next chat request:148+149+```ts150+const prompts = await fetch('/api/mcp-prompts').then((r) => r.json())151+152+await fetch('/api/chat', {153+ method: 'POST',154+ headers: { 'content-type': 'application/json' },155+ body: JSON.stringify({156+ messages,157+ threadId: 'thread-1',158+ promptName: prompts[0]?.name,159+ promptArgs: { tone: 'short' },@@ -0,0 +120,21 @@120+ : {}),121+ }122+ return client123+ }124+ const saved = await options.tokenStore.load()125+ if (!saved?.client) return undefined126+ client = {127+ client_id: saved.client.clientId,128+ ...(saved.client.clientSecret129+ ? { client_secret: saved.client.clientSecret }130+ : {}),131+ ...(saved.client.issuer ? { issuer: saved.client.issuer } : {}),132+ }133+ return client134+ },135+ saveClientInformation: (information) => {136+ client = information137+ },138+ tokens: async () => {139+ // Fresh-auth path: never surface tokens so the SDK starts authorization.140+ if (!options.useSavedTokens) return undefined@@ -0,0 +247,21 @@247+ options: CreateMCPClientWithOAuthRedirectOptions,248+): Promise<MCPClientWithOAuthResult> {249+ const saved = await options.tokenStore.load()250+ let authorizationUrl: string | undefined251+ const provider = await tokenStoreProvider(252+ {253+ redirectUri: options.callbackUrl,254+ clientName: options.clientName ?? 'TanStack AI',255+ scopes: options.scopes,256+ tokenStore: options.tokenStore,257+ useSavedTokens: Boolean(saved?.accessToken),258+ },259+ {260+ onRedirect: (url) => {261+ authorizationUrl = url.href262+ },263+ },264+ )265+266+ try {267+ const client = await createMCPClient({@@ -9,7 +77,15 @@77+ *78+ * Keep in sync with `@tanstack/ai`'s internal79+ * `activities/chat/mcp/resource-parts.ts` (used by `chat({ mcp })`).80+ *81+ * Do not pass this function directly to `Array.map` — map supplies an index as82+ * the second argument. Use `.map((block) => mcpResourceToContentPart(block))`.983 */10-export function mcpResourceToContentPart(content: {11- uri?: string12- text?: string13- blob?: string14- [key: string]: unknown15-}): ContentPart {84+export function mcpResourceToContentPart(85+ content: McpResourceContent,86+ options: McpResourceToContentPartOptions & { onReject: 'omit' },87+): ContentPart | null88+export function mcpResourceToContentPart(89+ content: McpResourceContent,90+ options?: Omit<McpResourceToContentPartOptions, 'onReject'> & {91+ onReject?: 'placeholder' | 'throw'
Pushed7b3dd43
Pushed894f110
- @@ -0,0 +151,21 @@151+152+return toServerSentEventsResponse(stream)153+```154+155+In the client, send the prompt the user picked (and its args). `useChat` streams the SSE answer into `messages`:156+157+```tsx158+import { useChat } from '@tanstack/ai-react'159+import { fetchServerSentEvents } from '@tanstack/ai-client'160+161+// From your prompt picker + argument form (not hard-coded to prompts[0]).162+const selectedPromptName = userSelectedPrompt.name163+const promptArgs = userSelectedPromptArgs164+165+export function ChatWithPrompt() {166+ const { messages, sendMessage } = useChat({167+ threadId: 'thread-1',168+ connection: fetchServerSentEvents('/api/chat', {169+ body: {170+ promptName: selectedPromptName,171+ promptArgs,
Pushed969f253
- @@ -0,0 +114,21 @@114+ const prompts = await mcp.prompts()115+ return Response.json(prompts)116+}117+```118+119+On the chat server, read the prompt from `forwardedProps` (where120+`fetchServerSentEvents({ body })` puts it) and return SSE:121+122+```ts123+// api/chat.ts124+import {125+ chat,126+ chatParamsFromRequest,127+ toServerSentEventsResponse,128+} from '@tanstack/ai'129+import { openaiText } from '@tanstack/ai-openai'130+131+const { messages, threadId, forwardedProps } =132+ await chatParamsFromRequest(request)133+const promptName = forwardedProps.promptName134+const promptArgs = forwardedProps.promptArgs
Pushedeb9a4fa
Pushed8752691
tanstack-source reviewed
@@ -0,0 +65,21 @@65+async function tokenStoreProvider(66+ options: {67+ redirectUri: string68+ clientName: string69+ scopes: ReadonlyArray<string> | undefined70+ tokenStore: McpTokenStore71+ /** When true, `tokens()` returns saved credentials (reconnect path). */72+ useSavedTokens: boolean73+ },74+ hooks: {75+ onRedirect?: (url: URL) => void76+ },77+): Promise<OAuthClientProvider> {78+ let client: StoredOAuthClientInformation | undefined79+ let verifier = ''80+ let discovery: OAuthDiscoveryState | undefined81+ // Fresh-auth / callback start: hide pre-existing store tokens so the SDK82+ // begins authorization. After `saveTokens`, flip this so the new bearer is83+ // available for the post-callback connection.84+ let allowStoredTokens = options.useSavedTokens85+ const pending = await options.tokenStore.loadPending?.()@@ -155,0 +317,21 @@317+ `MCP resource "${uri}" was read but every content block was omitted ` +318+ `(resourcePartOptions.onReject: 'omit')`,319+ )320+ }321+ }322+ }323+324+ return { promptMessages, contentParts }325+ }326+327+ async #resolveResourceUris(328+ attach: ChatMCPAttachResources,329+ signal?: AbortSignal,330+ ): Promise<Array<string>> {331+ if ('uris' in attach) return [...attach.uris]332+ const max = attach.max ?? 8333+ const uris: Array<string> = []334+ for (const source of this.#sources) {335+ const list = source.listResources ?? source.resources336+ if (!list) continue337+ const listed = await list.call(source, {@@ -179,3 +200,7 @@179200 Object.entries(clients).map(([key, c]) => [key, c.getInfo()]),180201 )181202 },203+ async resources(options?: {204+ signal?: AbortSignal205+ }): Promise<Array<{ uri: string; name?: string; mimeType?: string }>> {206+ const listed = await Promise.all(@@ -155,0 +286,21 @@286+ : `MCP prompt "${ref.name}" was not found on any mcp.clients source`,287+ {288+ cause:289+ errors.length > 0 ? new AggregateError(errors) : undefined,290+ },291+ )292+ }293+ }294+ }295+296+ if (this.#attachResources) {297+ const uris = await this.#resolveResourceUris(this.#attachResources, signal)298+ for (const uri of uris) {299+ const result = await readUriFromSources(300+ this.#sources,301+ uri,302+ this.#requestMeta,303+ )304+ if (!result) {305+ throw new Error(306+ `MCP resource "${uri}" could not be read (no client implements readResource)`,
Applied a fix from CI3502e93
tanstack-source reviewed
@@ -74,0 +86,21 @@86+87+// Start / reconnect88+const result = await createMCPClientWithOAuthRedirect({89+ url: 'https://mcp.notion.com/mcp',90+ callbackUrl: 'https://app.example.com/oauth/mcp/callback',91+ tokenStore,92+})93+94+if (result.status === 'redirect') {95+ // Send the user to result.authorizationUrl96+} else {97+ // result.client is ready for chat({ mcp: { clients: [result.client] } })98+}99+100+// Callback route101+const client = await finishMCPOAuthRedirect({102+ url: 'https://mcp.notion.com/mcp',103+ callbackUrl: 'https://app.example.com/oauth/mcp/callback',104+ tokenStore,105+ code: searchParams.get('code')!,106+})@@ -0,0 +22,21 @@22+23+function isRecord(value: unknown): value is Record<string, unknown> {24+ return typeof value === 'object' && value !== null && !Array.isArray(value)25+}26+27+function readMcpUrl(metadata: Readonly<Record<string, unknown>> | undefined) {28+ const payload = metadata?.['tanstack:interruptPayload']29+ if (!isRecord(payload)) return undefined30+ // URL mode may arrive as kind 'url', or as a form-shaped request with a url field.31+ if (!isRecord(payload.request)) return undefined32+ const url = payload.request.url33+ if (typeof url !== 'string') return undefined34+ return {35+ kind: payload.kind,36+ message: payload.request.message,37+ url,38+ }39+}40+41+export function McpUrlElicitation() {42+ const { interrupts } = useChat({@@ -0,0 +289,21 @@289+ }290+ await persistPending(options.tokenStore, provider)291+ return { status: 'redirect', authorizationUrl }292+}293+294+/**295+ * Finish an OAuth redirect: exchange `code`, save tokens, return a connected296+ * MCP client. Call this from your callback route.297+ *298+ * Prefer `callbackParams` (the full callback query) when the authorization299+ * server may send `iss`. `code` + optional `iss` also works.300+ */301+export async function finishMCPOAuthRedirect(302+ options: CreateMCPClientWithOAuthRedirectOptions &303+ (304+ | { callbackParams: URLSearchParams; code?: never; iss?: never }305+ | { code: string; iss?: string; callbackParams?: never }306+ ),307+): Promise<MCPClient> {308+ const provider = await tokenStoreProvider(309+ {
Pushed7a64b9b
github-actions[bot](GitHub profile, opens in a new tab) added labelsmerge-conflicts
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: maintainer
Sign in to join this conversation.
🦋 Changeset detected#
Latest commit: 7a64b9b14abc77a537feab790764aacd0607935a
The changes in this PR will be included in the next version bump.
This PR includes changesets to release 3 packages
Not sure what this means? Click here to learn what changesets are.
Click here if you're a maintainer who wants to add another changeset to this PR