Add: Sampling Example to README

This commit is contained in:
Rishi Nandha Vanchi 2025-06-25 20:08:15 +05:30 • committed by GitHub
commit 7a64f97493
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -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<CreateMessageResult> {
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: