Open History to see the last commit
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 ask a model for a draft and return it."
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
17`sample` lets an MCP tool call a model for a draft, such as a short note. The tool itself has no model.
18
19Call it as `ctx.context.sample` inside the tool.
20
21## Quick setup
22
23You need an MCP server first. If you do not have one, start with [Serve Tools over HTTP](./server).
24
251. Give `.server()` the type `MCPToolContext`, so `ctx.context.sample` type-checks.
262. Call `ctx.context.sample` with the messages for the model.
273. Pass a `sample` function to `createMCPServer`. It answers the sample request.
28
29```ts
30import { toolDefinition } from '@tanstack/ai'
31import { createMCPServer } from '@tanstack/ai-mcp/server'
32import type { MCPToolContext } from '@tanstack/ai-mcp/server'
33import { z } from 'zod'
34
35const draftNote = toolDefinition({
36 name: 'draft_note',
37 description: 'Draft a short note about a topic',
38 inputSchema: z.object({
39 topic: z.string(),
40 }),
41}).server<MCPToolContext>(async (args, ctx) => {
42 const draft = await ctx.context.sample({
43 messages: [
44 {
45 role: 'user',
46 content: `Write a short note about ${args.topic}.`,
47 },
48 ],
49 })
50
51 if (typeof draft !== 'string') {
52 throw new Error('The sample result is not text.')
53 }
54
55 return draft
56})
57
58const server = createMCPServer({
59 name: 'notes',
60 version: '1.0.0',
61 tools: [draftNote],
62 sample: async (request) => {
63 const first = request.messages[0]
64 const content = first === undefined ? '' : first.content
65 return `Draft: ${content}`
66 },
67})
68
69export function handleMcp(request: Request) {
70 return server.fetch(request)
71}
72```
73
74Call `draft_note` with a topic. The tool result is the draft text. In this example, the `sample` function returns `Draft:` plus the message. In your app, call your model there.
75
76## How it works
77
78- `ctx.context.sample` is a method on the context of the tool.
79- The `sample` function has the type `(request) => Promise<unknown>`.
80- Who answers depends on the MCP spec version of the client. See the table below.
81
82## Advanced
83
84### Spec 2025 and spec 2026
85
86| Spec | Result |
87| --- | --- |
88| Spec 2025 | `ctx.context.sample` asks the MCP client. It does not call the `sample` function. |
89| Spec 2026 | `ctx.context.sample` calls the `sample` function. It does not ask the client. |
90| Spec 2026 with no `sample` | `ctx.context.sample` throws an Error. The message names `sample`. |
91
92On spec 2025, the server can ask the client only when it keeps a session. Without a session, `ctx.context.sample` calls the `sample` function. See [MCP Server Sessions](./server-sessions).