### Full MCP Application Setup Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/15-mcp-apps/code/typescript/my-app/dist/mcp-app.html A complete example of an MCP application, including creation, middleware, routes, static file serving, registration, and starting the runtime. This represents a typical deployment scenario. ```typescript const app = MCP.createApp({ middleware: [ async (req, res, next) => { console.log('Logging request'); next(); } ], routes: { '/': { GET: { handler: async (req, res) => { res.send('Welcome!'); } } }, '/users/:id': { GET: { handler: async (req, res) => { res.send(`User: ${req.params.id}`); } } } }, static: { '/static': './public' } }); MCP.registerApp('main-app', app); MCP.start(); ``` -------------------------------- ### Install and Run Host Application Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/15-mcp-apps/ext-apps/examples/basic-host/README.md Install dependencies and start the host application. The default server URL is http://localhost:3001/mcp. ```bash npm install npm run start # Open http://localhost:8080 ``` -------------------------------- ### Install and Run Basic Host Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/pcm/03-GettingStarted/15-mcp-apps/ext-apps/examples/basic-host/README.md Install dependencies and start the basic host application. The host defaults to connecting to a local MCP server. Configure alternative server URLs using the SERVERS environment variable. ```bash npm install npm run start # Open http://localhost:8080 ``` ```bash SERVERS='["http://localhost:1234/mcp", "http://localhost:5678/mcp"]' npm run start ``` -------------------------------- ### MCP App Start Example Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/15-mcp-apps/code/typescript/my-app/dist/mcp-app.html Example of starting the MCP application. ```typescript startMcpApp(); ``` -------------------------------- ### Full LLM Client Setup and Request Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/pcm/03-GettingStarted/03-llm-client/README.md Provides a complete C# example demonstrating the setup of the LLM client, including authentication, transport configuration, tool fetching, request definition, and initial model call. ```csharp using Azure; using Azure.AI.Inference; using Azure.Identity; using System.Text.Json; using ModelContextProtocol.Client; using ModelContextProtocol.Protocol; var endpoint = "https://models.inference.ai.azure.com"; var token = Environment.GetEnvironmentVariable("GITHUB_TOKEN"); // Your GitHub Access Token var client = new ChatCompletionsClient(new Uri(endpoint), new AzureKeyCredential(token)); var chatHistory = new List { new ChatRequestSystemMessage("You are a helpful assistant that knows about AI") }; var clientTransport = new StdioClientTransport(new() { Name = "Demo Server", Command = "/workspaces/mcp-for-beginners/03-GettingStarted/02-client/solution/server/bin/Debug/net8.0/server", Arguments = [], }); Console.WriteLine("Setting up stdio transport"); await using var mcpClient = await McpClient.CreateAsync(clientTransport); ChatCompletionsToolDefinition ConvertFrom(string name, string description, JsonElement jsonElement) { // convert the tool to a function definition FunctionDefinition functionDefinition = new FunctionDefinition(name) { Description = description, Parameters = BinaryData.FromObjectAsJson(new { Type = "object", Properties = jsonElement }, new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }) }; // create a tool definition ChatCompletionsToolDefinition toolDefinition = new ChatCompletionsToolDefinition(functionDefinition); return toolDefinition; } async Task> GetMcpTools() { Console.WriteLine("Listing tools"); var tools = await mcpClient.ListToolsAsync(); List toolDefinitions = new List(); foreach (var tool in tools) { Console.WriteLine($"Connected to server with tools: {tool.Name}"); Console.WriteLine($"Tool description: {tool.Description}"); Console.WriteLine($"Tool parameters: {tool.JsonSchema}"); JsonElement propertiesElement; tool.JsonSchema.TryGetProperty("properties", out propertiesElement); var def = ConvertFrom(tool.Name, tool.Description, propertiesElement); Console.WriteLine($"Tool definition: {def}"); toolDefinitions.Add(def); Console.WriteLine($"Properties: {propertiesElement}"); } return toolDefinitions; } // 1. List tools on mcp server var tools = await GetMcpTools(); for (int i = 0; i < tools.Count; i++) { var tool = tools[i]; Console.WriteLine($"MCP Tools def: {i}: {tool}"); } // 2. Define the chat history and the user message var userMessage = "add 2 and 4"; chatHistory.Add(new ChatRequestUserMessage(userMessage)); // 3. Define options, including the tools var options = new ChatCompletionsOptions(chatHistory) { Model = "gpt-4.1-mini", Tools = { tools[0] } }; // 4. Call the model ``` -------------------------------- ### Minimal MCP App Setup Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/15-mcp-apps/code/typescript/my-app/dist/mcp-app.html A barebones example of an MCP application, showing the essential parts needed to initialize and run. ```typescript import { McpApp } from "@mcp/core"; const app = new McpApp({ id: "minimal-app", version: "1.0.0", name: "Minimal App", description: "Minimal MCP app.", author: "Coder", license: "MIT", entryPoint: "./dist/minimal-app.js", icon: "./icon.png", permissions: [], }); app.run(); ``` -------------------------------- ### Setup Development Environment and Run Scripts Source: https://github.com/microsoft/mcp-for-beginners/blob/main/06-CommunityContributions/README.md Clone the repository, install dependencies, and run scripts for schema validation, documentation checks, formatting, and local preview. Ensure you fork the repository to your own username first. ```bash # Fork the repository git clone https://github.com/YOUR-USERNAME/modelcontextprotocol.git cd modelcontextprotocol # Install dependencies npm install # For schema changes, validate and generate schema.json: npm run check:schema:ts npm run generate:schema # For documentation changes npm run check:docs npm run format # Preview documentation locally (optional): npm run serve:docs ``` -------------------------------- ### Full MCP Application Setup and Execution Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/15-mcp-apps/code/typescript/my-app/dist/mcp-app.html This snippet covers the entire process of setting up an MCP application: creating it, defining its routes and middleware, registering it with the MCP runtime, and finally starting the runtime to make it live. ```typescript const app = MCP.createApp({ middleware: [ async (req, res, next) => { console.log('Executing app middleware'); next(); } ], routes: { '/': { GET: { handler: async (req, res) => { res.send('MCP App is running'); } } } } }); MCP.registerApp('my-web-app', app); MCP.start(); ``` -------------------------------- ### Server Execution Example Source: https://github.com/microsoft/mcp-for-beginners/blob/main/05-AdvancedTopics/mcp-realtimesearch/README.md This snippet demonstrates how to execute a web search query using the MCP client and start a search server. It includes setting search parameters and connecting the transport. ```javascript const searchResults = await client.callTool({ name: 'web_search', arguments: { query: 'Model Context Protocol implementation examples', maxResults: 10, timePeriod: 'week', includeDomains: ['github.com', 'docs.microsoft.com'] } }); console.log('Search results:', searchResults); // Cleanup await client.disconnect(); } // Start the server const transport = new StreamableHTTPServerTransport(); await searchServer.connect(transport); console.log('Search server running at http://localhost:8000/mcp'); // In a separate process or after server is started // connectToSearchServer().catch(console.error); ``` -------------------------------- ### Setup MCP Development Environment Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/pcm/06-CommunityContributions/README.md Commands to fork, clone, install dependencies, and run schema/documentation checks for the MCP project. Use these to set up your local environment for contributing. ```bash git clone https://github.com/YOUR-USERNAME/modelcontextprotocol.git cd modelcontextprotocol npm install npm run check:schema:ts npm run generate:schema npm run check:docs npm run format npm run serve:docs ``` -------------------------------- ### Setup Development Environment for MCP Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/en/06-CommunityContributions/README.md Commands to clone the repository, install dependencies, and run validation/formatting scripts for MCP development. Use these to set up your local environment for contributing. ```bash git clone https://github.com/YOUR-USERNAME/modelcontextprotocol.git cd modelcontextprotocol npm install npm run check:schema:ts npm run generate:schema npm run check:docs npm run format npm run serve:docs ``` -------------------------------- ### Install Dependencies with uv or pip Source: https://github.com/microsoft/mcp-for-beginners/blob/main/05-AdvancedTopics/web-search-mcp/README.md Commands to install project dependencies. uv is recommended for faster installations. ```bash # Using uv (recommended) uv pip install -r requirements.txt # Using pip pip install -r requirements.txt ``` -------------------------------- ### Run the .NET Server Sample Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/01-first-server/solution/dotnet/README.md Execute this command to start the .NET server application. Ensure dependencies are restored first. ```bash dotnet run ``` -------------------------------- ### Load Testing Framework Example Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/en/11-MCPServerHandsOnLabs/08-Testing/README.md This Python code snippet demonstrates a basic setup for a load testing framework. It's a starting point for simulating user load on an application. ```python import time import threading def task(name): """Simulate a task that takes some time.""" print(f"Thread {name}: starting time.sleep(1) print(f"Thread {name}: finishing def main(): threads = [] for i in range(5): t = threading.Thread(target=task, args=(i,)) threads.append(t) t.start() for t in threads: t.join() if __name__ == "__main__": main() ``` -------------------------------- ### Install Dependencies and Start TypeScript/JavaScript Project Source: https://github.com/microsoft/mcp-for-beginners/blob/main/AGENTS.md Commands to install npm dependencies and start a TypeScript or JavaScript project. ```bash cd npm install npm start ``` -------------------------------- ### Install Docker Desktop using Homebrew Source: https://github.com/microsoft/mcp-for-beginners/blob/main/11-MCPServerHandsOnLabs/03-Setup/README.md Installs Docker Desktop on macOS using Homebrew. After installation, launch Docker Desktop and complete the initial setup wizard. ```bash # Download from https://desktop.docker.com/mac/stable/Docker.dmg # Or use Homebrew brew install --cask docker ``` -------------------------------- ### Setup Logging, Metrics, and Configuration Source: https://github.com/microsoft/mcp-for-beginners/blob/main/11-MCPServerHandsOnLabs/01-Architecture/README.md Initializes logging, metrics, and configuration for infrastructure management. Ensure logging handlers and levels are configured appropriately. ```python class InfrastructureManager: """Infrastructure concerns management.""" def __init__(self): self.logger = self._setup_logging() self.metrics = self._setup_metrics() self.config = self._load_configuration() def _setup_logging(self) -> Logger: """Configure structured logging.""" logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=[ logging.StreamHandler(), logging.FileHandler('mcp_server.log') ] ) return logging.getLogger(__name__) ``` -------------------------------- ### Generate Contribution Guide Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/en/11-MCPServerHandsOnLabs/12-Best-Practices/README.md Generates a structured guide for community contributors, outlining setup, contribution areas, and community resources. ```python from typing import Dict class CommunityContributor: """Tools for community engagement and contribution.""" @staticmethod def generate_contribution_guide(): """Generate personalized contribution guide.""" return { "getting_started": { "setup": "Follow setup guide in Lab 03", "first_contribution": "Start with documentation improvements", "testing": "Run full test suite before submitting PR" }, "contribution_areas": { "documentation": "Improve learning labs and examples", "testing": "Add test cases and improve coverage", "features": "Implement new MCP tools and capabilities", "performance": "Optimize queries and caching", "security": "Enhance security measures and validation" }, "community_resources": { "discord": "https://discord.com/invite/ByRwuEEgH4", "discussions": "GitHub Discussions for Q&A", "issues": "GitHub Issues for bug reports", "examples": "Share your implementation examples" } } @staticmethod def validate_contribution(pr_data: Dict) -> Dict[str, bool]: """Validate contribution meets standards.""" return { "has_tests": "test" in pr_data.get("files_changed", []), "has_documentation": "README" in str(pr_data.get("files_changed", [])), "follows_conventions": True, # Would implement actual checks "security_reviewed": pr_data.get("security_review", False), "performance_tested": pr_data.get("benchmark_results", False) } ``` -------------------------------- ### MCP App Configuration Example Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/15-mcp-apps/code/typescript/my-app/dist/mcp-app.html A comprehensive example of an MCP application configuration, including name, version, and dependencies. This serves as a template for app setup. ```typescript const appConfig = { name: "my-app", version: "1.0.0" }; const app = new McpApp(appConfig); app.addDependency("mcp-app-dependency-1"); app.addDependency("mcp-app-dependency-2"); app.registerService("my-service", async () => { return { // Service implementation }; }); export default app.build(); ``` -------------------------------- ### Load Testing Framework Setup Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/pcm/11-MCPServerHandsOnLabs/08-Testing/README.md This Python code snippet demonstrates the basic setup for a load testing framework. It is intended to be a starting point for performance testing your MCPServer. ```python import time import threading def test_case(thread_id): # Simulate a request to the server print(f"Thread {thread_id}: Starting request") time.sleep(1) # Simulate network latency and processing time print(f"Thread {thread_id}: Request finished") def run_load_test(num_threads): threads = [] for i in range(num_threads): thread = threading.Thread(target=test_case, args=(i,)) threads.append(thread) thread.start() for thread in threads: thread.join() if __name__ == "__main__": num_concurrent_requests = 10 print(f"Starting load test with {num_concurrent_requests} concurrent requests...") run_load_test(num_concurrent_requests) print("Load test finished.") ``` -------------------------------- ### Set up and Populate Test Database Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/ar/11-MCPServerHandsOnLabs/10-Deployment/README.md Configures the test database by running create_schema.sql and populating it with sample data using generate_sample_data.py. Uses environment variables for database connection details. ```bash PGPASSWORD=postgres psql -h localhost -U postgres -d retail_test -f scripts/create_schema.sql python scripts/generate_sample_data.py --test ``` -------------------------------- ### MCP App Initialization Example Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/15-mcp-apps/code/typescript/my-app/dist/mcp-app.html Example of initializing the MCP app with configuration. ```typescript const appConfig: McpAppConfig = { appName: 'MyAwesomeApp', version: '1.0.0' }; initializeMcpApp(appConfig); ``` -------------------------------- ### Test Job Configuration Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/sw/11-MCPServerHandsOnLabs/10-Deployment/README.md Configures the test job, including the runner, service dependencies (PostgreSQL), and steps for checkout, Python setup, dependency installation, database setup, and running tests. ```yaml jobs: test: runs-on: ubuntu-latest services: postgres: image: pgvector/pgvector:pg16 env: POSTGRES_PASSWORD: postgres POSTGRES_DB: retail_test options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 5432:5432 steps: - name: Checkout code uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v4 with: python-version: '3.11' cache: 'pip' - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.lock.txt pip install pytest pytest-cov pytest-asyncio - name: Set up test database run: | PGPASSWORD=postgres psql -h localhost -U postgres -d retail_test -f scripts/create_schema.sql python scripts/generate_sample_data.py --test env: POSTGRES_HOST: localhost POSTGRES_PORT: 5432 POSTGRES_DB: retail_test POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres - name: Run tests run: | pytest tests/ -v --cov=mcp_server --cov-report=xml --cov-report=html env: POSTGRES_HOST: localhost POSTGRES_PORT: 5432 POSTGRES_DB: retail_test POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres PROJECT_ENDPOINT: ${{ secrets.TEST_PROJECT_ENDPOINT }} AZURE_CLIENT_ID: ${{ secrets.TEST_AZURE_CLIENT_ID }} AZURE_CLIENT_SECRET: ${{ secrets.TEST_AZURE_CLIENT_SECRET }} AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} - name: Upload coverage reports uses: codecov/codecov-action@v3 with: file: ./coverage.xml flags: unittests ``` -------------------------------- ### Set up Python Virtual Environment and Install MCP Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/01-first-server/README.md Create a Python virtual environment, activate it, and then install the MCP package with CLI support. ```bash # Create a virtual env and install dependencies python -m venv venv venv\Scripts\activate pip install "mcp[cli]" ``` -------------------------------- ### Setup MCP Inspector Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/pcm/10-StreamliningAIWorkflowsBuildingAnMCPServerWithAIToolkit/lab3/code/weather_mcp/README.md Sets up the MCP Inspector by navigating to the inspector directory and installing its Node.js dependencies. ```bash cd inspector && npm install ``` -------------------------------- ### Build and Run Java Server Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/01-first-server/README.md First, build the Java project with Maven, then run the generated JAR file to start the server. ```bash ./mvnw clean install -DskipTests java -jar target/calculator-server-0.0.1-SNAPSHOT.jar ``` -------------------------------- ### Initialize Rust Project Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/01-first-server/README.md Create a new Rust project and navigate into its directory. ```bash mkdir calculator-server cd calculator-server cargo init ``` -------------------------------- ### Community Contribution Guide Generation Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/pcm/11-MCPServerHandsOnLabs/12-Best-Practices/README.md Generates a personalized contribution guide for community members, including setup instructions, contribution areas, and community resources. Also includes a function to validate contributions against defined standards. ```python from typing import Dict class CommunityContributor: """Tools for community engagement and contribution.""" @staticmethod def generate_contribution_guide(): """Generate personalized contribution guide.""" return { "getting_started": { "setup": "Follow setup guide in Lab 03", "first_contribution": "Start with documentation improvements", "testing": "Run full test suite before submitting PR" }, "contribution_areas": { "documentation": "Improve learning labs and examples", "testing": "Add test cases and improve coverage", "features": "Implement new MCP tools and capabilities", "performance": "Optimize queries and caching", "security": "Enhance security measures and validation" }, "community_resources": { "discord": "https://discord.com/invite/ByRwuEEgH4", "discussions": "GitHub Discussions for Q&A", "issues": "GitHub Issues for bug reports", "examples": "Share your implementation examples" } } @staticmethod def validate_contribution(pr_data: Dict) -> Dict[str, bool]: """Validate contribution meets standards.""" return { "has_tests": "test" in pr_data.get("files_changed", []), "has_documentation": "README" in str(pr_data.get("files_changed", [])), "follows_conventions": True, # Would implement actual checks "security_reviewed": pr_data.get("security_review", False), "performance_tested": pr_data.get("benchmark_results", False) } ``` -------------------------------- ### MCP Application with GraphQL Client Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/15-mcp-apps/code/typescript/my-app/dist/mcp-app.html Example of using a GraphQL client to query data. This assumes a GraphQL client library is installed. ```typescript import { GraphQLClient } from "graphql-request"; const client = new GraphQLClient("/graphql", { headers: { authorization: "Bearer YOUR_API_TOKEN", }, }); const query = ` query GetUsers { users { id name } } `; async function fetchUsers() { const data = await client.request(query); console.log(JSON.stringify(data, null, 2)); } ``` -------------------------------- ### Custom Hook Example (TypeScript) Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/15-mcp-apps/code/typescript/my-app/dist/mcp-app.html Illustrates creating a custom hook to encapsulate reusable logic. Custom hooks start with 'use'. ```typescript import React, { useState, useEffect } from "react"; function useDocumentTitle(title: string) { useEffect(() => { document.title = title; }, [title]); } function TitleChanger() { useDocumentTitle("My Awesome App"); return
Check the document title!
; } export default TitleChanger; ``` -------------------------------- ### Sample Output Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/03-llm-client/solution/python/README.md This is an example of the expected output when running the `client.py` script. It shows the resource listing, tool information, and the result of an LLM call. ```text LISTING RESOURCES Resource: ('meta', None) Resource: ('nextCursor', None) Resource: ('resources', []) INFO Processing request of type ListToolsRequest server.py:534 LISTING TOOLS Tool: add Tool {'a': {'title': 'A', 'type': 'integer'}, 'b': {'title': 'B', 'type': 'integer'}} CALLING LLM TOOL: {'function': {'arguments': '{"a":2,"b":20}', 'name': 'add'}, 'id': 'call_BCbyoCcMgq0jDwR8AuAF9QY3', 'type': 'function'} [05/08/25 21:04:55] INFO Processing request of type CallToolRequest server.py:534 TOOLS result: [TextContent(type='text', text='22', annotations=None)] ``` -------------------------------- ### Full LLM Client Setup and Interaction Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/03-llm-client/README.md Initializes the LLM client, sets up the transport, defines tools, and prepares for a chat interaction. ```csharp using Azure; using Azure.AI.Inference; using Azure.Identity; using System.Text.Json; using ModelContextProtocol.Client; using ModelContextProtocol.Protocol; var endpoint = "https://models.inference.ai.azure.com"; var token = Environment.GetEnvironmentVariable("GITHUB_TOKEN"); // Your GitHub Access Token var client = new ChatCompletionsClient(new Uri(endpoint), new AzureKeyCredential(token)); var chatHistory = new List { new ChatRequestSystemMessage("You are a helpful assistant that knows about AI") }; var clientTransport = new StdioClientTransport(new() { Name = "Demo Server", Command = "/workspaces/mcp-for-beginners/03-GettingStarted/02-client/solution/server/bin/Debug/net8.0/server", Arguments = [], }); Console.WriteLine("Setting up stdio transport"); await using var mcpClient = await McpClient.CreateAsync(clientTransport); ChatCompletionsToolDefinition ConvertFrom(string name, string description, JsonElement jsonElement) { // convert the tool to a function definition FunctionDefinition functionDefinition = new FunctionDefinition(name) { Description = description, Parameters = BinaryData.FromObjectAsJson(new { Type = "object", Properties = jsonElement }, new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }) }; // create a tool definition ChatCompletionsToolDefinition toolDefinition = new ChatCompletionsToolDefinition(functionDefinition); return toolDefinition; } async Task> GetMcpTools() { Console.WriteLine("Listing tools"); var tools = await mcpClient.ListToolsAsync(); List toolDefinitions = new List(); foreach (var tool in tools) { Console.WriteLine($"Connected to server with tools: {tool.Name}"); Console.WriteLine($"Tool description: {tool.Description}"); Console.WriteLine($"Tool parameters: {tool.JsonSchema}"); JsonElement propertiesElement; tool.JsonSchema.TryGetProperty("properties", out propertiesElement); var def = ConvertFrom(tool.Name, tool.Description, propertiesElement); Console.WriteLine($"Tool definition: {def}"); toolDefinitions.Add(def); Console.WriteLine($"Properties: {propertiesElement}"); } return toolDefinitions; } // 1. List tools on mcp server var tools = await GetMcpTools(); for (int i = 0; i < tools.Count; i++) { var tool = tools[i]; Console.WriteLine($"MCP Tools def: {i}: {tool}"); } // 2. Define the chat history and the user message var userMessage = "add 2 and 4"; chatHistory.Add(new ChatRequestUserMessage(userMessage)); // 3. Define options, including the tools ``` -------------------------------- ### Product Recommendation Engine Setup Source: https://github.com/microsoft/mcp-for-beginners/blob/main/11-MCPServerHandsOnLabs/07-Semantic-Search/README.md This Python code sets up a basic product recommendation engine. Ensure necessary libraries are installed. ```python import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity # Load the dataset df = pd.read_csv('products.csv') # Initialize TF-IDF Vectorizer vectorizer = TfidfVectorizer(stop_words='english') # Fit and transform the product descriptions tfidf_matrix = vectorizer.fit_transform(df['description']) # Calculate cosine similarity cosine_sim = cosine_similarity(tfidf_matrix, tfidf_matrix) def get_recommendations(product_id, num_recommendations=5): # Get the index of the product product_index = df[df['id'] == product_id].index[0] # Get the similarity scores for the product sim_scores = list(enumerate(cosine_sim[product_index])) # Sort products based on similarity scores sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) # Get the scores of the top N products sim_scores = sim_scores[1:num_recommendations+1] # Get the product indices product_indices = [i[0] for i in sim_scores] # Return the recommended products return df['name'].iloc[product_indices] # Example usage: recommendations = get_recommendations(product_id=1) print(recommendations) ``` -------------------------------- ### Configure SerpAPI Key Source: https://github.com/microsoft/mcp-for-beginners/blob/main/05-AdvancedTopics/web-search-mcp/README.md Example of creating a .env file to store your SerpAPI key. Replace 'your_serpapi_key_here' with your actual key. ```bash SERPAPI_KEY=your_serpapi_key_here ``` -------------------------------- ### Load Testing Framework Setup Source: https://github.com/microsoft/mcp-for-beginners/blob/main/11-MCPServerHandsOnLabs/08-Testing/README.md This Python code sets up a basic framework for load testing. It requires the 'locust' library to be installed. ```python from locust import HttpUser, task, between class WebsiteUser(HttpUser): wait_time = between(1, 5) def on_start(self): self.client.post("/login", json={"username":"testuser", "password":"testpass"}) @task def index(self): self.client.get("/") @task def profile(self): self.client.get("/users/me") ``` -------------------------------- ### Example MCP Client in TypeScript Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/02-client/README.md Demonstrates a complete example of an MCP client in TypeScript, including connecting via stdio transport and invoking various server functionalities like listing prompts and resources, getting a prompt, reading a resource, and calling a tool. ```typescript import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; const transport = new StdioClientTransport({ command: "node", args: ["server.js"] }); const client = new Client( { name: "example-client", version: "1.0.0" } ); await client.connect(transport); // List prompts const prompts = await client.listPrompts(); // Get a prompt const prompt = await client.getPrompt({ name: "example-prompt", arguments: { arg1: "value" } }); // List resources const resources = await client.listResources(); // Read a resource const resource = await client.readResource({ uri: "file:///example.txt" }); // Call a tool const result = await client.callTool({ name: "example-tool", arguments: { arg1: "value" } }); ``` -------------------------------- ### Run the Client Application Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/02-client/solution/typescript/README.md Start the client application using this npm script. Ensure the project is built first. ```bash npm run client ``` -------------------------------- ### Complete LangChain4j LLM Client Example Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/pcm/03-GettingStarted/03-llm-client/README.md A full example demonstrating the setup and usage of the LangChain4j LLM client with MCP tools. This includes configuring the chat model, transport, MCP client, tool provider, and the bot service, followed by sample chat interactions. ```java public class LangChain4jClient { public static void main(String[] args) throws Exception { ChatLanguageModel model = OpenAiOfficialChatModel.builder() .isGitHubModels(true) .apiKey(System.getenv("GITHUB_TOKEN")) .timeout(Duration.ofSeconds(60)) .modelName("gpt-4.1-nano") .timeout(Duration.ofSeconds(60)) .build(); McpTransport transport = new HttpMcpTransport.Builder() .sseUrl("http://localhost:8080/sse") .timeout(Duration.ofSeconds(60)) .logRequests(true) .logResponses(true) .build(); McpClient mcpClient = new DefaultMcpClient.Builder() .transport(transport) .build(); ToolProvider toolProvider = McpToolProvider.builder() .mcpClients(List.of(mcpClient)) .build(); Bot bot = AiServices.builder(Bot.class) .chatLanguageModel(model) .toolProvider(toolProvider) .build(); try { String response = bot.chat("Calculate the sum of 24.5 and 17.3 using the calculator service"); System.out.println(response); response = bot.chat("What's the square root of 144?"); System.out.println(response); response = bot.chat("Show me the help for the calculator service"); System.out.println(response); } finally { mcpClient.close(); } } } ``` -------------------------------- ### Python MCP Client Example Source: https://context7.com/microsoft/mcp-for-beginners/llms.txt Demonstrates how to use the MCP client to connect to a server, initialize a session, call a tool, and handle server notifications. ```python import asyncio from mcp import ClientSession, types from mcp.client.streamable_http import streamablehttp_client async def message_handler(message): if isinstance(message, types.ServerNotification): print("NOTIFICATION:", message.params.data) # prints each progress update else: print("SERVER MESSAGE:", message) async def run(): async with streamablehttp_client("http://localhost:8000/mcp") as (read, write, _): async with ClientSession(read, write, message_handler=message_handler) as session: await session.initialize() result = await session.call_tool("process_files", arguments={"message": "batch-1"}) print("Final result:", result.content) # NOTIFICATION: Processing document 1/10 # NOTIFICATION: Processing document 2/10 ... (10 notifications) # Final result: [TextContent(type='text', text='Done processing: batch-1')] asyncio.run(run()) ``` -------------------------------- ### Advanced Debugging Framework Example Source: https://github.com/microsoft/mcp-for-beginners/blob/main/11-MCPServerHandsOnLabs/08-Testing/README.md This Python code snippet demonstrates the use of an advanced debugging framework. Ensure the framework is installed and configured before use. ```python import pytest def test_advanced_debugging(): # Placeholder for advanced debugging logic assert True ``` -------------------------------- ### Checkout and Python Setup Steps Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/km/11-MCPServerHandsOnLabs/10-Deployment/README.md Includes steps to checkout the code from the repository and set up the Python environment with version 3.11 and pip caching. ```yaml steps: - name: Checkout code uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v4 with: python-version: '3.11' cache: 'pip' ``` -------------------------------- ### MCP App Data Persistence Example Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/15-mcp-apps/code/typescript/my-app/dist/mcp-app.html Shows how to use the MCP data store to set and get values. This is useful for saving application state. ```typescript await app.data.set("lastLogin", new Date()); const lastLogin = await app.data.get("lastLogin"); console.log("Last login was:", lastLogin); ``` -------------------------------- ### Start an MCP App Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/15-mcp-apps/code/typescript/my-app/dist/mcp-app.html Shows how to start a specific registered MCP application. ```bash mcp-cli start my-app ``` -------------------------------- ### Python Setup for Publishing MCP Tools Source: https://github.com/microsoft/mcp-for-beginners/blob/main/06-CommunityContributions/README.md Commands to package and upload an MCP tool to a distribution index. Ensure you have the necessary build and upload tools installed. ```bash python setup.py sdist bdist_wheel python -m twine upload dist/* ``` -------------------------------- ### Kafka MCP Client Example Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/pcm/05-AdvancedTopics/mcp-realtimestreaming/README.md Demonstrates how to create an MCP client, connect it using the Kafka transport, initialize the session, execute a tool, and shut down gracefully. Ensure Kafka is running and topics are configured. ```python async def kafka_mcp_example(): # Create MCP client with Kafka transport client = Client( {"name": "kafka-mcp-client", "version": "1.0.0"}, ClientCapabilities({}) ) # Create and connect the Kafka transport transport = KafkaMCPTransport( bootstrap_servers="localhost:9092", input_topic="mcp-responses", output_topic="mcp-requests" ) await client.connect(transport) try: # Initialize the MCP session await client.initialize() # Example of executing a tool via MCP response = await client.execute_tool( "process_data", { "data": "sample data", "metadata": { "source": "sensor-1", "timestamp": "2025-06-12T10:30:00Z" } } ) print(f"Tool execution response: {response}") # Clean shutdown await client.shutdown() finally: await transport.close() # Run the example if __name__ == "__main__": asyncio.run(kafka_mcp_example()) ``` -------------------------------- ### Basic MCP App Handler Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/15-mcp-apps/code/typescript/my-app/dist/mcp-app.html A minimal example of an MCP application handler for a GET request on the root path. It simply sends a 'Hello World!' response. ```typescript async (req, res) => { res.send('Hello World!'); } ``` -------------------------------- ### Example .env File Contents Source: https://github.com/microsoft/mcp-for-beginners/blob/main/11-MCPServerHandsOnLabs/03-Setup/README.md Illustrates the expected contents of the .env file after Azure resource deployment, including endpoints, model names, credentials, and database configuration for development. ```bash # .env file contents PROJECT_ENDPOINT=https://your-project.cognitiveservices.azure.com/ AZURE_OPENAI_ENDPOINT=https://your-openai.openai.azure.com/ EMBEDDING_MODEL_DEPLOYMENT_NAME=text-embedding-3-small AZURE_CLIENT_ID=your-client-id AZURE_CLIENT_SECRET=your-client-secret AZURE_TENANT_ID=your-tenant-id APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=your-key;... # Database configuration (for development) POSTGRES_HOST=localhost POSTGRES_PORT=5432 POSTGRES_DB=zava POSTGRES_USER=postgres POSTGRES_PASSWORD=your-secure-password ``` -------------------------------- ### MCP App Direct Path Request Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/15-mcp-apps/code/typescript/my-app/dist/mcp-app.html This example shows how to make a direct path request to an MCP application. It sends a GET request to the '/users' endpoint. ```typescript app.directPath("/users", "GET"); ``` -------------------------------- ### Create .NET MCP Server with Tools Source: https://github.com/microsoft/mcp-for-beginners/blob/main/01-CoreConcepts/README.md Demonstrates how to set up a basic MCP server in .NET, register a custom tool, and connect using the STDIO transport. Ensure the ModelContextProtocol.Server and ModelContextProtocol.Server.Transport namespaces are available. ```.NET using System; using System.Threading.Tasks; using ModelContextProtocol.Server; using ModelContextProtocol.Server.Transport; using ModelContextProtocol.Server.Tools; public class WeatherServer { public static async Task Main(string[] args) { // Create an MCP server var server = new McpServer( name: "Weather MCP Server", version: "1.0.0" ); // Register our custom weather tool server.AddTool("weatherTool", description: "Gets current weather for a location", execute: async (location) => { // Call weather API (simplified) var weatherData = await GetWeatherDataAsync(location); return weatherData; }); // Connect the server using stdio transport var transport = new StdioServerTransport(); await server.ConnectAsync(transport); Console.WriteLine("Weather MCP Server started"); // Keep the server running until process is terminated await Task.Delay(-1); } private static async Task GetWeatherDataAsync(string location) { // This would normally call a weather API // Simplified for demonstration await Task.Delay(100); // Simulate API call return new WeatherData { Temperature = 72.5, Conditions = "Sunny", Location = location }; } } public class WeatherData { public double Temperature { get; set; } public string Conditions { get; set; } public string Location { get; set; } } ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/microsoft/mcp-for-beginners/blob/main/AGENTS.md Commands to clone the MCP for Beginners repository and navigate into the project directory. ```bash git clone https://github.com/microsoft/mcp-for-beginners.git cd mcp-for-beginners ``` -------------------------------- ### Run MCP Server Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/en/04-PracticalImplementation/samples/python/README.md Start the MCP server in a terminal window. The server can also be run in development mode using the MCP CLI or installed in Claude Desktop. ```bash python server.py ``` ```bash mcp dev server.py ``` ```bash mcp install server.py ``` -------------------------------- ### Set Up Virtual Environment Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/10-advanced/code/python/README.md Create and activate a Python virtual environment to manage project dependencies. ```shell python -m venv venv source ./venv/bin/activate ``` -------------------------------- ### Client Example for Web Search Tool Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/pcm/05-AdvancedTopics/mcp-realtimesearch/README.md Demonstrates how a client can connect to the MCP search server using Streamable HTTP transport and call the 'web_search' tool. It shows initializing the client session and making a tool call with specific parameters. ```python from mcp.client import ClientSession, streamablehttp_client async def client_example(): # Connect to the search server using Streamable HTTP transport async with streamablehttp_client("http://localhost:8000/mcp") as (read, write, _): async with ClientSession(read, write) as session: # Initialize the connection await session.initialize() # Call the web_search tool search_results = await session.call_tool( "web_search", { "query": "latest developments in AI and Model Context Protocol", "max_results": 5, "time_period": "day", "include_domains": ["github.com", "microsoft.com"] } ) print(f"Search results: {search_results}") ```