From 7a64f974936fd27faf063df8f9e952740bce9ad4 Mon Sep 17 00:00:00 2001 From: Rishi Nandha Vanchi <49914358+RishiNandha@users.noreply.github.com> Date: Wed, 25 Jun 2025 20:08:15 +0530 Subject: [PATCH] Add: Sampling Example to README --- README.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/README.md b/README.md index aa8f9304..0d8d8f7c 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ - [Tools](#tools) - [Prompts](#prompts) - [Completions](#completions) + - [Sampling](#sampling) - [Running Your Server](#running-your-server) - [stdio](#stdio) - [Streamable HTTP](#streamable-http) @@ -382,6 +383,37 @@ import { getDisplayName } from "@modelcontextprotocol/sdk/shared/metadataUtils.j const displayName = getDisplayName(tool); ``` +### Sampling + +MCP servers can also request MCP client LLMs for responses. Below is an example of a sampling request sent just after connecting to the Client + +```typescript +// Result sent back from LLM follow the CreateMessageSchema +import {CreateMessageResult} from "@modelcontextprotocol/sdk/types.js"; + +// Async Function to send a sampling request to the LLM at top-level +async function samplingExample(server: McpServer): Promise { + const samplingText = "Text prompt to send to LLM"; + const result = await McpServer.server.createMessage( + { + messages : [{ + role: "user", + content: { + text: samplingText, + type: "text" + } + }], + maxTokens: 1000 + } + ); + return result; +} + +// Sampling request just after connecting to MCP Client +server.connect(transport); +samplingExample(server); +``` + ## Running Your Server MCP servers in TypeScript need to be connected to a transport to communicate with clients. How you start the server depends on the choice of transport: