MCP Sampling Server
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
MCP Sampling Server
A Model Context Protocol (MCP) server that demonstrates the sampling feature in TypeScript. This server shows how MCP servers can request LLM completions from connected clients, enabling agentic behaviors without requiring server-side API keys.
What is MCP Sampling?
Sampling in MCP allows servers to request LLM generations from clients. This enables:
Server-side intelligence without API keys
Client-controlled model access and permissions
Flexible model selection based on client capabilities
Agentic workflows where tools can leverage LLM capabilities
Related MCP server: ask-llm-mcp
Features
This server implements seven tools and four resources that demonstrate sampling, elicitation, roots, and resources:
Sampling Examples
π summarize-text: Summarizes any text using LLM sampling
π analyze-sentiment: Analyzes text sentiment with confidence scores
π generate-story: Creates creative stories based on prompts
β ask-question: Answers questions with optional context
Elicitation Examples
π€ create-user-profile: Interactive profile creation that uses sampling to gather missing information
π product-review-wizard: Multi-step survey with conditional questions based on user responses
Roots Integration
ποΈ analyze-workspace: Demonstrates the roots feature by requesting workspace roots from the client and using sampling to provide intelligent analysis and recommendations
Prerequisites
Node.js 18 or higher
npm or yarn package manager
Installation
Clone or navigate to the project directory:
cd MCP-SamplingInstall dependencies:
npm install
Running the Server
Development Mode (with hot reload)
npm run devProduction Mode
# Build the TypeScript code
npm run build
# Run the compiled JavaScript
npm startThe server will start on http://localhost:3000/mcp
Testing the Server
Using MCP Inspector
The easiest way to test your server is with the MCP Inspector:
npx @modelcontextprotocol/inspector http://localhost:3000/mcpUsing Claude for Desktop
Note: The client must support the sampling capability for these tools to work.
Add to your Claude Desktop configuration (~/Library/Application Support/Claude/claude_desktop_config.json on macOS):
{
"mcpServers": {
"sampling-demo": {
"url": "http://localhost:3000/mcp"
}
}
}Using Claude Code CLI
claude mcp add --transport http sampling-demo http://localhost:3000/mcpExample Usage
Once connected to a client, you can try:
Text Summarization
Use the summarize-text tool to summarize this article: [paste long text]Sentiment Analysis
Analyze the sentiment of this review: "The product exceeded my expectations!"Story Generation
Generate a short story about a robot learning to paintQuestion Answering
Ask a question: What are the benefits of using the Model Context Protocol?Interactive Profile Creation (Elicitation)
Create a user profile
(The tool will use sampling to request missing information like name, age, occupation, and interests)Product Review Wizard (Multi-step Elicitation)
Start a product review
(The wizard will guide you through multiple steps: product selection, rating, feedback, and conditional follow-up questions)Workspace Analysis (Roots Feature)
Use the analyze-workspace tool
(The tool will request roots from the client, analyze your workspace structure, and provide intelligent recommendations)Using Resources
Access resources through your MCP client:
- mcp://server/info - View server information
- mcp://samples/1 - Read sample data by ID (1, 2, or 3)
- mcp://snippets/positive - Access text snippets by category
- mcp://analyzed/review1 - Get AI-analyzed text samplesHow Sampling Works
When a tool is called:
Tool receives input from the client (e.g., text to summarize)
Server creates a sampling request using
mcpServer.server.createMessage()Client receives the request and may show it to the user for approval
Client executes the LLM call using its configured model
Response is sent back to the server
Server processes and returns the result to the client
How Elicitation Works
Elicitation is the process of gathering missing information from users interactively. This implementation demonstrates two approaches:
Single-Step Elicitation (create-user-profile)
When required fields are missing, the tool uses sampling to request all missing information at once:
Detects which required fields are not provided
Uses
createMessage()to ask the LLM to prompt the user for missing dataParses the response to extract the provided information
Combines the elicited data with any originally provided values
Uses sampling again to generate a personalized summary
Multi-Step Elicitation (product-review-wizard)
Implements a guided wizard pattern with conditional questions:
Step-by-step flow: Each call advances through predefined steps (start β rating β feedback β complete)
Conditional logic: Low ratings trigger additional questions about improvements
State tracking: The tool maintains the survey state across multiple calls
Sentiment analysis: Uses sampling to analyze the final feedback
Both approaches demonstrate how MCP servers can create interactive, conversational experiences by leveraging the sampling capability.
π For detailed examples and usage patterns, see ELICITATION_EXAMPLES.md
How Resources Work
Resources in MCP expose data to LLMs without performing significant computation or having side effects. Unlike tools (which are model-controlled), resources are application-driven, meaning MCP clients decide how to expose them.
This server implements four types of resources:
Static Resources (
mcp://server/info): Server metadata and configurationDynamic Resources (
mcp://samples/{id}): Data served based on URI parametersCategorized Content (
mcp://snippets/{category}): Pre-defined text snippetsAI-Enhanced Resources (
mcp://analyzed/{textId}): Resources that use sampling for intelligent data access
Key capabilities:
π¦ Expose structured data without side effects
π Use URI templates for dynamic content
π― Combine with sampling for AI-enhanced data
π Support multiple MIME types (JSON, text, markdown)
π Application-controlled access patterns
π For complete implementation details, see RESOURCES_IMPLEMENTATION.md
How Roots Integration Works
This server implements the roots feature to demonstrate workspace-aware functionality. The analyze-workspace tool:
Requests roots from the client using
roots/listHandles gracefully when roots aren't supported
Combines with sampling to analyze workspace structure
Generates intelligent insights about the workspace organization
Provides recommendations based on the workspace structure
Key capabilities:
ποΈ Discovers available workspace directories
π§ Uses AI to analyze project structure
π‘ Provides context-aware recommendations
π Demonstrates proper security boundaries
π Combines multiple MCP features effectively
π For complete implementation details, see ROOTS_IMPLEMENTATION.md
Sample Code
const response = await mcpServer.server.createMessage({
messages: [
{
role: 'user',
content: {
type: 'text',
text: 'Please summarize: ' + text
}
}
],
maxTokens: 500,
modelPreferences: {
hints: [{ name: 'claude-3-sonnet' }],
intelligencePriority: 0.8,
speedPriority: 0.5,
costPriority: 0.3
}
});Model Preferences
The server uses model preferences to guide client model selection:
hints: Suggest specific models (e.g.,
claude-3-sonnet)intelligencePriority (0-1): How important are advanced capabilities?
speedPriority (0-1): How important is low latency?
costPriority (0-1): How important is minimizing cost?
Clients are free to map these preferences to their available models.
Project Structure
MCP-Sampling/
βββ src/
β βββ index.ts # Main server implementation
βββ dist/ # Compiled JavaScript (after build)
βββ package.json # Dependencies and scripts
βββ tsconfig.json # TypeScript configuration
βββ .gitignore # Git ignore rules
βββ README.md # Main documentation
βββ ELICITATION_EXAMPLES.md # Elicitation feature examples
βββ ROOTS_IMPLEMENTATION.md # Roots feature implementation guideKey Concepts
Resources in MCP
Resources expose data to LLMs in a structured way without computation or side effects. They are fundamentally different from tools:
Tools are model-controlled and can take actions
Resources are application-controlled and provide read-only data
Resource Types:
Static resources: Fixed data like configuration or documentation
Dynamic resources: Parameterized data using URI templates
AI-enhanced resources: Combine resources with sampling for intelligent data access
Example:
mcpServer.registerResource(
'sample-data',
new ResourceTemplate('mcp://samples/{id}', { list: undefined }),
{
title: 'Sample Data',
description: 'Example data by ID'
},
async (uri, params) => {
const id = Array.isArray(params.id) ? params.id[0] : params.id;
return {
contents: [{
uri: uri.href,
mimeType: 'application/json',
text: JSON.stringify(data[id], null, 2)
}]
};
}
);Security Considerations
Human in the loop: Clients SHOULD require user approval for sampling requests
User control: Users should be able to review and edit prompts
Rate limiting: Clients should implement appropriate rate limits
Data handling: Both parties must handle sensitive data appropriately
Client Requirements
For sampling to work, clients must:
Declare the
samplingcapability during initializationHandle
sampling/createMessagerequestsImplement user approval flows (recommended)
Return properly formatted responses
Troubleshooting
Server won't start
Ensure Node.js 18+ is installed:
node --versionCheck if port 3000 is available:
lsof -i :3000(macOS/Linux)Install dependencies:
npm install
Tools not working
Verify the client supports the
samplingcapabilityCheck server logs for errors
Ensure the client has model access and API keys configured
Sampling requests fail
The client must approve sampling requests (check client UI)
Verify the client has LLM access configured
Check network connectivity between client and server
Roots in MCP
What are Roots?
Roots in MCP provide a standardized way for clients to expose filesystem locations to servers. They define the boundaries of where servers can operate within the filesystem, establishing clear access controls and workspace contexts.
Key Concepts
Workspace Boundaries: Roots define which directories and files a server has access to
Client-Controlled: Clients expose roots to servers, maintaining security and user control
Dynamic Updates: Clients can notify servers when the list of roots changes
Multiple Roots: Support for multiple project directories, repositories, or workspaces
How Roots Work
Client declares roots capability during initialization
Server requests roots using the
roots/listmethodClient returns accessible locations (e.g., project directories)
Server respects root boundaries in all operations
Client notifies of changes when roots are added/removed
Root Structure
Each root includes:
uri: Unique identifier (must be a
file://URI)name: Optional human-readable name for display
Example root:
{
"uri": "file:///home/user/projects/myproject",
"name": "My Project"
}Protocol Messages
Listing Roots (Server β Client)
{
"jsonrpc": "2.0",
"id": 1,
"method": "roots/list"
}Response (Client β Server)
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"roots": [
{
"uri": "file:///home/user/projects/frontend",
"name": "Frontend Repository"
},
{
"uri": "file:///home/user/projects/backend",
"name": "Backend Repository"
}
]
}
}Root List Changed Notification (Client β Server)
{
"jsonrpc": "2.0",
"method": "notifications/roots/list_changed"
}Client Capabilities
Clients supporting roots declare the capability during initialization:
{
"capabilities": {
"roots": {
"listChanged": true
}
}
}listChanged indicates whether the client will emit notifications when roots change.
Security Considerations
Clients MUST:
Only expose roots with appropriate permissions
Validate all root URIs to prevent path traversal attacks
Implement proper access controls
Prompt users for consent before exposing roots
Monitor root accessibility
Servers SHOULD:
Check for roots capability before requesting
Handle cases where roots become unavailable
Respect root boundaries during all operations
Validate all paths against provided roots
Handle root list changes gracefully
Use Cases
Project Workspaces: Expose project directories to enable context-aware operations
Multi-Repository Development: Work across multiple related repositories
Sandboxed Operations: Limit server access to specific directories
Version Control Integration: Automatically detect and expose VCS roots
Monorepo Support: Expose multiple packages within a monorepo structure
Implementation in This Server
This server implements roots functionality in the analyze-workspace tool, which demonstrates:
Requesting roots from the client:
const rootsResponse = await mcpServer.server.request(
{ method: 'roots/list', params: {} },
z.object({
roots: z.array(z.object({
uri: z.string(),
name: z.string().optional()
}))
})
);Storing and using roots information:
if (rootsResponse && rootsResponse.roots) {
clientRoots = rootsResponse.roots;
}Combining roots with sampling:
The tool requests workspace roots from the client
Uses LLM sampling to analyze the workspace structure
Generates intelligent recommendations based on the roots
Provides context-aware insights about the workspace
Graceful handling when roots aren't supported:
if (clientRoots.length === 0) {
return {
content: [{
type: 'text',
text: 'No roots available. The client may not support the roots capability.'
}]
};
}This demonstrates how servers can combine multiple MCP features (roots + sampling) to provide sophisticated, context-aware functionality.
Benefits of Using Roots
π Enhanced Security: Clear boundaries for server operations
π― Context Awareness: Servers understand their workspace context
π Dynamic Updates: Adapt to changing project structures
π₯ User Control: Users explicitly grant filesystem access
ποΈ Multi-Project Support: Work across multiple projects simultaneously
Learn More
License
MIT License - See LICENSE file for details
Contributing
Contributions are welcome! This is a demonstration project to help developers understand MCP sampling.
Built with β€οΈ using the Model Context Protocol
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogβ¦
This server cannot be deployed
Maintenance
Related MCP Connectors
Text generation over MCP: prose, emails, blog outlines, SQL, humanizing, text diffs, fake data.
Use AI models for chat, image, and video generation from Claude Code and other MCP hosts.
MCP-Native LLM Orchestration Agent
Query, browse, and automate OmegaAI workspaces from any MCP client. Streamable HTTP with OAuth 2.0.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceEnables developers to explain error messages, validate and format JSON, generate regex patterns from descriptions, and summarize text via an LLM, all through MCP-connected clients.-
- AlicenseAqualityCmaintenanceEnables MCP clients to send raw text prompts to inexpensive LLM models via the Devin/Windsurf backend, returning answers in result files to avoid context bloat, with support for multi-turn sessions and model discovery.3MIT
- AlicenseNot gradedqualityBmaintenanceEnables chat, document search (RAG), and a declarative SQL tool builder over MCP so any client can use these capabilities.AGPL 3.0
- AlicenseNot gradedqualityAmaintenanceEnables MCP-compatible applications to interact with local and cloud-hosted LLM models for model management, text generation, chat, embeddings, and web search/fetch.817 npmAGPL 3.0