### 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(); ``` -------------------------------- ### Complete LLM Client Example with LangChain4j Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/03-llm-client/README.md A full Java example demonstrating the setup of an LLM client using LangChain4j to interact with MCP services. This includes model configuration, transport setup, and tool integration. ```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(); } } } ``` -------------------------------- ### 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(); ``` -------------------------------- ### 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 ``` -------------------------------- ### User Authentication and Request State Setup Decorator Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/zh-MO/11-MCPServerHandsOnLabs/02-Security/README.md This decorator verifies user authentication and populates the request state with user information and accessible stores. It handles unauthorized and forbidden access errors. ```python def authenticate_user(func: Callable) -> Callable: """Decorator to authenticate user and set request state.""" @functools.wraps(func) async def wrapper(*args, **kwargs): # Get request object request = None for arg in args: if isinstance(arg, Request): request = arg break if not request: raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Request object not found" ) # Get user info from request headers auth_header = request.headers.get('Authorization') if not auth_header: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Authorization header missing", headers={"WWW-Authenticate": "Bearer"} ) try: # Extract token and validate token = auth_header.split(" ")[1] user_info = await get_user_info_from_token(token) user_stores = await get_accessible_stores(user_info['user_id']) if not user_stores: raise AuthorizationError( detail="No store access configured for user" ) # Set default store context (first accessible store) request.state.current_store = user_stores[0] request.state.accessible_stores = user_stores # Add user info to request state request.state.user_info = user_info request.state.user_id = user_info['user_id'] # Call the original function return await func(*args, **kwargs) except ValueError as e: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail=str(e), headers={"WWW-Authenticate": "Bearer"} ) except AuthorizationError as e: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=str(e) ) return wrapper return decorator ``` -------------------------------- ### 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 ``` -------------------------------- ### Check System Resources Usage Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/ur/11-MCPServerHandsOnLabs/11-Monitoring/README.md Monitors CPU, memory, and disk usage to detect potential performance bottlenecks. It triggers a warning if any resource exceeds 85% utilization. Requires the 'psutil' library to be installed. ```python import psutil # Placeholder for DiagnosticResult and config objects class DiagnosticResult: def __init__(self, check_name, status, message, details=None, remediation=None): self.check_name = check_name self.status = status self.message = message self.details = details if details is not None else {} self.remediation = remediation async def _check_system_resources(self) -> DiagnosticResult: """Check system resource usage.""" try: cpu_percent = psutil.cpu_percent(interval=1) memory = psutil.virtual_memory() disk = psutil.disk_usage('/') warnings = [] if cpu_percent > 85: warnings.append(f"High CPU usage: {cpu_percent:.1f}%") if memory.percent > 85: warnings.append(f"High memory usage: {memory.percent:.1f}%") if disk.percent > 85: warnings.append(f"High disk usage: {disk.percent:.1f}%") details = { "cpu_percent": cpu_percent, "memory_percent": memory.percent, "memory_available_gb": memory.available / (1024**3), "disk_percent": disk.percent, "disk_free_gb": disk.free / (1024**3) } if warnings: return DiagnosticResult( check_name="system_resources", status="warning", message=f"Resource warnings: {'; '.join(warnings)}", details=details, remediation="Monitor resource usage and consider scaling" ) else: return DiagnosticResult( check_name="system_resources", status="pass", message="System resources normal", details=details ) except Exception as e: return DiagnosticResult( check_name="system_resources", status="fail", message=f"Resource check failed: {str(e)}", details={"error": str(e)} ) ``` -------------------------------- ### 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() ``` -------------------------------- ### Trace Operation Execution with MCPDebugger Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/zh-CN/11-MCPServerHandsOnLabs/08-Testing/README.md Use the `trace_execution` context manager to log the start, end, and duration of operations. It captures execution time, status (running, completed, error), and any exceptions raised. ```python async with self.trace_execution(f"tool_execution_{tool_name}", {'parameters': parameters}) as trace: # Pre-execution validation validation_result = await self._validate_tool_parameters(tool_name, parameters) trace['validation'] = validation_result if not validation_result['valid']: return { 'success': False, 'error': f"Parameter validation failed: {validation_result['errors']}", 'debug_info': trace } # Database connection check db_health = await self._check_database_health() trace['database_health'] = db_health # Execute tool with monitoring try: tool_instance = self.server.get_tool(tool_name) if not tool_instance: return { 'success': False, 'error': f"Tool '{tool_name}' not found", 'debug_info': trace } # Monitor resource usage during execution start_memory = await self._get_memory_usage() result = await tool_instance.call(**parameters) end_memory = await self._get_memory_usage() trace.update({ 'memory_start_mb': start_memory, 'memory_end_mb': end_memory, 'memory_used_mb': end_memory - start_memory, 'result_success': result.success, 'result_row_count': result.row_count }) return { 'success': result.success, 'data': result.data, 'error': result.error, 'metadata': result.metadata, 'debug_info': trace } except Exception as e: trace['exception'] = { 'type': type(e).__name__, 'message': str(e), 'traceback': traceback.format_exc() } return { 'success': False, 'error': f"Tool execution failed: {str(e)}", ``` -------------------------------- ### MCP Server Setup with WebSearchHandler Source: https://github.com/microsoft/mcp-for-beginners/blob/main/05-AdvancedTopics/mcp-realtimesearch/README.md Demonstrates initializing the `WebSearchHandler`, setting up the MCP server lifespan to manage its lifecycle, and registering a web search tool. ```python # Initialize the search handler search_handler = WebSearchHandler( api_endpoint="https://api.search-service.example/search", api_key="your-api-key-here" ) # Setup lifespan to manage the search handler @asyncio.asynccontextmanager async def app_lifespan(server: FastMCP): """Manage application lifecycle""" await search_handler.initialize() try: yield {"search_handler": search_handler} finally: await search_handler.close() # Set lifespan for the server search_server = FastMCP("WebSearch", lifespan=app_lifespan) # Register a web search tool @search_server.tool() async def web_search(query: str, max_results: int = 5, include_domains: List[str] = None, exclude_domains: List[str] = None, time_period: str = "any") -> Dict[str, Any]: """ Search the web for information Args: query: The search query max_results: Maximum number of results to return (default: 5) include_domains: List of domains to include in search results exclude_domains: List of domains to exclude from search results time_period: Time period for results ("day", "week", "month", "any") Returns: Dictionary containing search results """ ctx = search_server.get_context() search_handler = ctx.request_context.lifespan_context["search_handler"] results = await search_handler.perform_search( query=query, max_results=max_results, include_domains=include_domains, exclude_domains=exclude_domains, time_period=time_period ) return results ``` -------------------------------- ### Install and Run TypeScript/JavaScript Projects Source: https://github.com/microsoft/mcp-for-beginners/blob/main/AGENTS.md Install dependencies and start a TypeScript or JavaScript project using npm. ```bash cd npm install npm start ``` -------------------------------- ### Install Docker on macOS using Homebrew Source: https://github.com/microsoft/mcp-for-beginners/blob/main/11-MCPServerHandsOnLabs/03-Setup/README.md Installs Docker on macOS using Homebrew. After installation, launch Docker Desktop from Applications and complete the setup wizard. ```bash 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__) ``` -------------------------------- ### Trace Operation Execution Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/vi/11-MCPServerHandsOnLabs/08-Testing/README.md An asynchronous context manager to trace the execution of an operation. It logs start and end times, execution duration, and captures errors with tracebacks. Useful for performance analysis and error tracking. ```python @asynccontextmanager def trace_execution(self, operation_name: str, context: Dict[str, Any] = None): """Trace operation execution with detailed logging.""" trace_id = f"{operation_name}_{int(time.time() * 1000)}" start_time = time.time() trace_info = { 'trace_id': trace_id, 'operation': operation_name, 'start_time': start_time, 'context': context or {}, 'status': 'running' } self.active_traces[trace_id] = trace_info logger.debug(f"Starting trace: {trace_id} - {operation_name}") try: yield trace_info # Success execution_time = time.time() - start_time trace_info.update({ 'status': 'completed', 'execution_time': execution_time }) logger.debug(f"Completed trace: {trace_id} in {execution_time:.3f}s") except Exception as e: # Error execution_time = time.time() - start_time trace_info.update({ 'status': 'error', 'execution_time': execution_time, 'error': str(e), 'traceback': traceback.format_exc() }) logger.logger.error(f"Error in trace: {trace_id} - {str(e)}") raise finally: # Store completed trace self.debug_logs.append(trace_info.copy()) del self.active_traces[trace_id] # Limit debug log size if len(self.debug_logs) > 1000: self.debug_logs = self.debug_logs[-500:] ``` -------------------------------- ### Install MCP Python Dependency Source: https://github.com/microsoft/mcp-for-beginners/blob/main/03-GettingStarted/05-stdio-server/README.md Installs the necessary 'mcp' Python package. This is a common troubleshooting step for servers not starting. ```bash pip install mcp ``` -------------------------------- ### Get Table Constraints Query Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/uk/11-MCPServerHandsOnLabs/06-Tools/README.md SQL query to retrieve constraint information for a table, including constraint name, type, associated columns, and foreign key details. ```sql SELECT constraint_name, constraint_type, column_name, foreign_table_name, foreign_column_name FROM information_schema.table_constraints tc LEFT JOIN information_schema.key_column_usage kcu ON tc.constraint_name = kcu.constraint_name LEFT JOIN information_schema.referential_constraints rc ON tc.constraint_name = rc.constraint_name LEFT JOIN information_schema.key_column_usage fkcu ON rc.unique_constraint_name = fkcu.constraint_name WHERE tc.table_schema = 'retail' AND tc.table_name = $1 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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(); ``` -------------------------------- ### 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); ``` -------------------------------- ### 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.") ``` -------------------------------- ### Example .env File Contents Source: https://github.com/microsoft/mcp-for-beginners/blob/main/11-MCPServerHandsOnLabs/03-Setup/README.md Example configuration for the .env file, including endpoints for project and Azure OpenAI, model deployment names, authentication credentials, and database connection details. ```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 ``` -------------------------------- ### 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]" ``` -------------------------------- ### 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 ``` -------------------------------- ### Example: Testing Calculator Tool Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/pcm/03-GettingStarted/13-mcp-inspector/README.md Demonstrates how to use the 'add' tool by providing parameters 'a' and 'b', and shows the expected response. ```json Tool: add Parameters: a: 25 b: 17 Response: { "content": [ { "type": "text", "text": "42" } ] } ``` -------------------------------- ### 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) } ``` -------------------------------- ### 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 ``` -------------------------------- ### 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; ``` -------------------------------- ### 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 ``` -------------------------------- ### 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)); } ``` -------------------------------- ### Python MCP Server Setup with Multi-Modal Tools Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/tl/05-AdvancedTopics/mcp-multi-modality/README.md Demonstrates how to initialize an MCP server and register custom tools, including those for multi-modal operations like image generation. This is the entry point for running an MCP server with extended functionalities. ```python from mcp_server import McpServer # Assuming AudioAnalysisTool and VideoFrameExtractionTool are defined elsewhere # from mcp_tools import AudioAnalysisTool, VideoFrameExtractionTool # Placeholder for other tools if not defined in the snippet class AudioAnalysisTool(Tool): def get_name(self): return "audioAnalysis" def get_description(self): return "Analyzes audio content" def get_schema(self): return {"type": "object", "properties": {"audio_data": {"type": "string"}}} async def execute_async(self, request: ToolRequest) -> ToolResponse: return ToolResponse(result={"analysis": "Placeholder analysis"}) class VideoFrameExtractionTool(Tool): def get_name(self): return "videoFrameExtraction" def get_description(self): return "Extracts frames from video" def get_schema(self): return {"type": "object", "properties": {"video_data": {"type": "string"}, "frame_number": {"type": "integer"}}} async def execute_async(self, request: ToolRequest) -> ToolResponse: return ToolResponse(result={"frame_data": "Placeholder frame data"}) # Main application async def main(): # Create server server = McpServer( name="Multi-Modal MCP Server", version="1.0.0", port=5000 ) # Register multi-modal tools server.register_tool(ImageGenerationTool()) server.register_tool(AudioAnalysisTool()) server.register_tool(VideoFrameExtractionTool()) # Start server await server.start() print("Multi-Modal MCP Server running on port 5000") if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### 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) ``` -------------------------------- ### 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)] ``` -------------------------------- ### 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") ``` -------------------------------- ### 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 ``` -------------------------------- ### 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" } }); ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### Advanced Debugging Framework Example Source: https://github.com/microsoft/mcp-for-beginners/blob/main/translations/my/11-MCPServerHandsOnLabs/08-Testing/README.md This Python code snippet demonstrates the setup for an advanced debugging framework. It requires specific imports to function correctly. ```python import sys import os import logging from mc import MCServer from mc.tools.debug import Debugger def main(): # Setup logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') # Initialize MCServer server = MCServer() # Initialize Debugger debugger = Debugger(server) # Example: Set a breakpoint debugger.set_breakpoint('player_join', lambda player: player.name == 'TestPlayer') # Example: Start debugging session debugger.start() # ... your server logic here ... # Example: Inspect a variable player_data = {'name': 'TestPlayer', 'id': 123} debugger.inspect(player_data, 'player_data') # Example: Step through code (if applicable in your framework) # debugger.step() # Example: Continue execution # debugger.continue_execution() logging.info("Debugging session ended.") if __name__ == "__main__": main() ``` -------------------------------- ### 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 ``` -------------------------------- ### 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; } } ``` -------------------------------- ### 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); ``` -------------------------------- ### Test TypeScript/JavaScript Code Samples Source: https://github.com/microsoft/mcp-for-beginners/blob/main/AGENTS.md Navigate to the specific sample directory and run npm install followed by npm test to validate the TypeScript/JavaScript code examples. ```bash # Navigate to specific sample and run its tests cd 03-GettingStarted/samples/typescript npm install && npm test ``` -------------------------------- ### 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 ``` -------------------------------- ### 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/* ``` -------------------------------- ### Verify PostgreSQL Database Setup Source: https://github.com/microsoft/mcp-for-beginners/blob/main/11-MCPServerHandsOnLabs/03-Setup/README.md Connect to the PostgreSQL container, inspect the database structure, and verify the presence of sample data in the retail schema. ```bash # Connect to PostgreSQL container docker-compose exec postgres psql -U postgres -d zava # Check database structure \dt retail.* # Verify sample data SELECT COUNT(*) FROM retail.stores; SELECT COUNT(*) FROM retail.products; SELECT COUNT(*) FROM retail.orders; # Exit PostgreSQL \q ``` -------------------------------- ### 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!'); } ``` -------------------------------- ### 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"); ```