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

server-sample.md

76 lines2.1 KB

1---
2title: Draft Text from a Tool
3id: mcp-server-sample
4order: 13
5description: "Call ctx.context.sample from an MCP server tool so the tool can return a draft."
6keywords:
7 - tanstack ai
8 - mcp
9 - model context protocol
10 - createMCPServer
11 - sample
12 - ctx.context.sample
13 - mcp server
14 - MCPToolContext
15---
16​
17You want the tool to return a draft. The tool has no model result yet.
18​
19Call `ctx.context.sample` inside the tool. Pass a `sample` function to `createMCPServer`. Give `.server()` the type `MCPToolContext`, so `ctx.context.sample` type-checks.
20​
21```ts
22import { toolDefinition } from '@tanstack/ai'
23import { createMCPServer } from '@tanstack/ai-mcp/server'
24import type { MCPToolContext } from '@tanstack/ai-mcp/server'
25import { z } from 'zod'
26​
27const draftNote = toolDefinition({
28 name: 'draft_note',
29 description: 'Draft a short note about a topic',
30 inputSchema: z.object({
31 topic: z.string(),
32 }),
33}).server<MCPToolContext>(async (args, ctx) => {
34 const draft = await ctx.context.sample({
35 messages: [
36 {
37 role: 'user',
38 content: `Write a short note about ${args.topic}.`,
39 },
40 ],
41 })
42​
43 if (typeof draft !== 'string') {
44 throw new Error('The sample result is not text.')
45 }
46​
47 return draft
48})
49​
50const server = createMCPServer({
51 name: 'notes',
52 version: '1.0.0',
53 tools: [draftNote],
54 sample: async (request) => {
55 const first = request.messages[0]
56 const content = first === undefined ? '' : first.content
57 return `Draft: ${content}`
58 },
59})
60​
61export function handleMcp(request: Request) {
62 return server.fetch(request)
64```
65​
66`ctx.context.sample` is a method on the context of the tool. The `sample` function is `(request) => Promise<unknown>`.
67​
68## Spec 2025 and spec 2026
69​
70| Spec | Result |
71| --- | --- |
72| Spec 2025 | `ctx.context.sample` asks the MCP client. It does not call the `sample` function. |
73| Spec 2026 | `ctx.context.sample` calls the `sample` function. It does not ask the client. |
74| Spec 2026 with no `sample` | `ctx.context.sample` throws an Error. The message names `sample`. |
75​
76Call `draft_note` with a topic. The tool result is the draft text.