### Quick Start Scenario: Install and Verify Prompts Source: https://github.com/microsoft/mcp/blob/main/docs/bug-bash/README.md Use these prompts during the 'Install and Verify' quick start scenario to check available tools and list resources. ```plaintext What Azure MCP tools are available? ``` ```plaintext Show me my subscriptions ``` ```plaintext List all resource groups in my subscription ``` -------------------------------- ### Complete Azure Monitor Setup Example Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/examples/python/generic-setup.md A full example demonstrating loading environment variables, configuring Azure Monitor, and application logic. ```python # app.py import os from dotenv import load_dotenv # Load environment variables load_dotenv() # Configure Azure Monitor FIRST from azure.monitor.opentelemetry import configure_azure_monitor configure_azure_monitor() # Now import and run your application import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def main(): logger.info("Application started") # Your application logic here logger.info("Application finished") if __name__ == "__main__": main() ``` -------------------------------- ### Install Copilot SDK for Go Source: https://github.com/microsoft/mcp/blob/main/servers/Azure.Mcp.Server/README.md Installs the Copilot SDK for Go using the go get command. This is a prerequisite for using the Go configuration example. ```bash go get github.com/github/copilot-sdk/go ``` -------------------------------- ### Multi-signal Example with Sdk.CreateTracerProviderBuilder and Sdk.CreateMeterProviderBuilder Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/api-reference/dotnet/SdkCreateTracerProviderBuilder.md Illustrates how to set up both tracing and metrics using separate builders. Each signal requires its own builder and disposal. This example also includes basic logging setup using LoggerFactory. ```csharp using System.Diagnostics; using System.Diagnostics.Metrics; using Microsoft.Extensions.Logging; using OpenTelemetry; using OpenTelemetry.Logs; using OpenTelemetry.Metrics; using OpenTelemetry.Trace; // Tracing using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource("MyApp") .AddConsoleExporter() .Build(); // Metrics using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter("MyApp") .AddConsoleExporter() .Build(); // Logging (uses ILoggerFactory, not a provider builder) using var loggerFactory = LoggerFactory.Create(builder => builder .AddOpenTelemetry(options => options.AddConsoleExporter())); var logger = loggerFactory.CreateLogger(); logger.LogInformation("Application started"); ``` -------------------------------- ### Example: Azure China Cloud with CLI Authentication and Server Start Source: https://github.com/microsoft/mcp/blob/main/docs/sovereign-clouds.md Demonstrates authenticating with Azure CLI for Azure China Cloud and then starting the MCP server with the same cloud configuration. ```bash # Authenticate with Azure CLI az cloud set --name AzureChinaCloud az login # Start the MCP server azmcp server start --cloud AzureChinaCloud ``` -------------------------------- ### Start MCP Server Locally Source: https://github.com/microsoft/mcp/blob/main/servers/Azure.Mcp.Server/docs/azmcp-commands.md Example of starting the MCP Server CLI locally using the .NET global tool. ```bash azmcp server start --mode namespace --transport=stdio ``` -------------------------------- ### Setup Sample Node.js Application Source: https://github.com/microsoft/mcp/blob/main/docs/bug-bash/scenarios/deployment.md Creates a basic Node.js Express application locally. This involves initializing the project, installing dependencies, and setting up a simple server script. ```bash mkdir bugbash-deploy-app && cd bugbash-deploy-app npm init -y npm install express cat > index.js << 'EOF' const express = require('express'); const app = express(); const port = process.env.PORT || 3000; app.get('/', (req, res) => { res.json({ message: 'Hello from Azure!', timestamp: new Date() }); }); app.listen(port, () => { console.log(`Server running on port ${port}`); }); EOF npm pkg set scripts.start="node index.js" ``` -------------------------------- ### Initialize Local Development Environment with SWA CLI Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.AzureBestPractices/src/Resources/azure-swa-best-practices.txt Install and initialize the SWA CLI for local development. Use `swa start` for local preview. ```bash npm install -g @azure/static-web-apps-cli npx swa init --yes npx swa build npx swa start # Local preview ``` -------------------------------- ### Example Live Test Setup for Storage Commands Source: https://github.com/microsoft/mcp/blob/main/servers/Azure.Mcp.Server/docs/new-command.md Demonstrates how to set up live tests for commands that interact with Azure resources. This setup works for both stdio and HTTP modes by using appropriate credentials and can be used to verify Azure SDK integration and RBAC permissions. ```csharp public class StorageCommandLiveTests : IAsyncLifetime { private readonly TestSettings _settings; public async Task InitializeAsync() { _settings = TestSettings.Load(); // Test infrastructure supports both modes: // - Stdio mode: Uses Azure CLI/VS Code credentials // - HTTP mode: Can simulate OBO or hosting environment identity } [Fact] public async Task ListStorageAccounts_ReturnsAccounts() { // Test works identically in both stdio and HTTP modes var result = await CallToolAsync( "azmcp_storage_account_list", new { subscription = _settings.SubscriptionId }); Assert.NotNull(result); } } ``` -------------------------------- ### Minimal Tracing Example with Sdk.CreateTracerProviderBuilder Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/api-reference/dotnet/SdkCreateTracerProviderBuilder.md Demonstrates the basic setup for tracing only using Sdk.CreateTracerProviderBuilder. Ensure you have the necessary OpenTelemetry packages installed. This example subscribes to an ActivitySource, configures a resource, adds a console exporter, and creates a span. ```csharp using System.Diagnostics; using OpenTelemetry; using OpenTelemetry.Trace; // 1. Define an ActivitySource var activitySource = new ActivitySource("MyApp"); // 2. Build a TracerProvider using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource("MyApp") .ConfigureResource(r => r.AddService("my-service")) .AddConsoleExporter() .Build(); // 3. Create spans using (var activity = activitySource.StartActivity("DoWork")) { activity?.SetTag("result", "ok"); } // TracerProvider.Dispose() is called by `using`, which flushes buffered spans. ``` -------------------------------- ### Corrected Published Executable Setup Source: https://github.com/microsoft/mcp/blob/main/servers/Fabric.Mcp.Server/TROUBLESHOOTING.md Ensures the server start command and arguments are correctly configured for published executables. ```json { "command": "/path/to/Fabric.Mcp.Server", "args": ["server", "start", "--mode", "all"] } ``` -------------------------------- ### Example Command: Initialize Project Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Extension/src/Resources/azd-best-practices.txt Example of initializing a project with a specific template and environment. ```bash command = "init --template todo-node" cwd = "/workspace" environmentName = "dev" ``` -------------------------------- ### Complete Program.cs with Azure Monitor and Services Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/examples/dotnet/aspnetcore-distro-setup.md A full example of Program.cs including service registrations, Azure Monitor setup, and pipeline configuration. ```csharp using Azure.Monitor.OpenTelemetry.AspNetCore; var builder = WebApplication.CreateBuilder(args); // Add services builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); // Add Azure Monitor OpenTelemetry builder.Services.AddOpenTelemetry().UseAzureMonitor(); var app = builder.Build(); // Configure pipeline if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); ``` -------------------------------- ### Example Command: Authenticate Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Extension/src/Resources/azd-best-practices.txt Example of logging into Azure, requiring the working directory. ```bash command = "auth login" cwd = "/workspace" ``` -------------------------------- ### Initialize Azure Monitor with ioredis Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/examples/nodejs/redis-setup.md This example shows how to initialize Azure Monitor for an application using the 'ioredis' package. The setup is identical to using the 'redis' package. ```javascript require('dotenv').config(); const { useAzureMonitor } = require('@azure/monitor-opentelemetry'); useAzureMonitor({ azureMonitorExporterOptions: { connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING } }); const Redis = require('ioredis'); const express = require('express'); const redis = new Redis(process.env.REDIS_URL); const app = express(); app.get('/api/cache/:key', async (req, res) => { const value = await redis.get(req.params.key); res.json({ key: req.params.key, value }); }); ``` -------------------------------- ### Start Azure MCP Server with Specific Cloud Source: https://github.com/microsoft/mcp/blob/main/servers/Azure.Mcp.Server/README.md These examples show how to start the Azure MCP server and direct it to authenticate against a specific Azure sovereign cloud using either a command-line argument or an environment variable. ```bash # Command line azmcp server start --cloud AzureChinaCloud ``` ```powershell # Environment variable (PowerShell) $env:AZURE_CLOUD = "AzureUSGovernment" azmcp server start ``` -------------------------------- ### Example Command: List Templates Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Extension/src/Resources/azd-best-practices.txt Example of listing project templates with the working directory specified. ```bash command = "template list" cwd = "/workspace" ``` -------------------------------- ### Check Missing Requirements with azsdk_verify_setup Source: https://github.com/microsoft/mcp/blob/main/eng/common/instructions/azsdk-tools/verify-setup.instructions.md Call verify setup with language and package path to identify missing requirements. The tool will list requirements that can be installed. ```bash azsdk_verify_setup(langs=javascript, packagePath=/azure-sdk-for-js) ``` -------------------------------- ### Start Development Server Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/examples/nodejs/nextjs-setup.md Command to start the Next.js development server. ```bash npm run dev ``` -------------------------------- ### Example Command: Configure Pipeline Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Extension/src/Resources/azd-best-practices.txt Example of configuring a CI/CD pipeline for a project in a specified environment. ```bash command = "pipeline config" cwd = "/workspace" environmentName = "test" ``` -------------------------------- ### Full Application Insights Setup with Options Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/api-reference/dotnet/AddApplicationInsightsTelemetry.md An example demonstrating how to configure Application Insights telemetry with specific options, including connection string, sampling ratio, and enabling JavaScript tracking. ```csharp using Microsoft.Extensions.DependencyInjection; using Microsoft.ApplicationInsights.AspNetCore.Extensions; var builder = WebApplication.CreateBuilder(args); builder.Services.AddApplicationInsightsTelemetry(options => { options.ConnectionString = "InstrumentationKey=...;IngestionEndpoint=..."; options.EnableQuickPulseMetricStream = true; options.SamplingRatio = 0.5f; // Collect 50% of telemetry options.EnableAuthenticationTrackingJavaScript = true; }); var app = builder.Build(); ``` -------------------------------- ### Full Multi-Signal OpenTelemetry Setup for ASP.NET Core Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/api-reference/dotnet/AddOpenTelemetry.md This example demonstrates configuring all three OpenTelemetry signals (tracing, metrics, and logging) for an ASP.NET Core application. It includes various instrumentations and OTLP exporters for each signal. Ensure logging providers are cleared if OpenTelemetry is the sole log sink. ```csharp using OpenTelemetry.Logs; using OpenTelemetry.Metrics; using OpenTelemetry.Trace; var builder = WebApplication.CreateBuilder(args); // Clear default log providers if you want OTel to be the sole log sink builder.Logging.ClearProviders(); builder.Services.AddOpenTelemetry() .ConfigureResource(r => r .AddService( serviceName: "my-web-api", serviceVersion: "1.0.0")) .WithTracing(tracing => tracing .AddAspNetCoreInstrumentation() .AddHttpClientInstrumentation() .AddSource("MyApp") .AddOtlpExporter()) .WithMetrics(metrics => metrics .AddAspNetCoreInstrumentation() .AddHttpClientInstrumentation() .AddMeter("MyApp") .AddOtlpExporter()) .WithLogging(logging => logging .AddOtlpExporter()); var app = builder.Build(); app.MapGet("/", () => "Hello World"); app.Run(); ``` -------------------------------- ### Standalone Tracing Setup Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/api-reference/dotnet/WithTracing.md Enable tracing in a standalone console application using `OpenTelemetrySdk.Create()`. This example configures a single ActivitySource and an OTLP exporter. The `OpenTelemetrySdk` instance must be disposed manually. ```csharp using OpenTelemetry; using OpenTelemetry.Trace; using var sdk = OpenTelemetrySdk.Create(builder => builder .WithTracing(tracing => tracing .AddSource("MyConsoleApp") .AddOtlpExporter())); // sdk.TracerProvider is available if needed ``` -------------------------------- ### Install Missing Requirements with azsdk_verify_setup Source: https://github.com/microsoft/mcp/blob/main/eng/common/instructions/azsdk-tools/verify-setup.instructions.md Use the tool again with the exact parameters and specify requirements to install. The tool will only install explicitly listed requirements. ```bash azsdk_verify_setup(langs=javascript, packagePath=/azure-sdk-for-js), requirementsToInstall=['pnpm', 'tsp']) ``` -------------------------------- ### Full Logging Configuration with OpenTelemetry Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/api-reference/dotnet/WithLogging.md This example demonstrates a comprehensive setup for OpenTelemetry logging, including resource configuration, custom log processors, OTLP export, and detailed logger options like including scopes and formatted messages. ```csharp using OpenTelemetry; using OpenTelemetry.Logs; using OpenTelemetry.Resources; var builder = WebApplication.CreateBuilder(args); builder.Services.AddOpenTelemetry() .ConfigureResource(r => r.AddService("order-api")) .WithLogging( configureBuilder: logging => logging .AddProcessor() .AddOtlpExporter(), configureOptions: options => { options.IncludeFormattedMessage = true; options.IncludeScopes = true; options.ParseStateValues = true; }); var app = builder.Build(); app.Run(); ``` -------------------------------- ### Install Entity Framework Core Instrumentation Package Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/api-reference/dotnet/EntityFrameworkInstrumentation.md Install the `OpenTelemetry.Instrumentation.EntityFrameworkCore` package to enable EF Core instrumentation. ```bash OpenTelemetry.Instrumentation.EntityFrameworkCore ``` -------------------------------- ### Install Azure Monitor and Django Packages Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/examples/python/django-setup.md Install the necessary packages using pip or add them to your requirements.txt file. ```bash pip install azure-monitor-opentelemetry django ``` ```text azure-monitor-opentelemetry django ``` -------------------------------- ### Install Azure Plugin Source: https://github.com/microsoft/mcp/blob/main/README.md Install the Azure plugin for Copilot CLI or Claude Code after adding the marketplace. ```bash /plugin install azure-skills@skills ``` -------------------------------- ### Install an Extension Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Extension/src/Resources/azd-best-practices.txt Installs a new extension for the Azure Developer CLI. ```bash azd extension install ``` -------------------------------- ### Install Dependencies Source: https://github.com/microsoft/mcp/blob/main/eng/common/tsp-client/README.md Navigate to the `eng/common/tsp-client` directory and install project dependencies using `npm ci`. ```bash # Navigate to this directory cd eng/common/tsp-client # Install dependencies npm ci ``` -------------------------------- ### Install GitHub Copilot SDK for Node.js Source: https://github.com/microsoft/mcp/blob/main/servers/Azure.Mcp.Server/README.md Install the necessary Node.js package for the GitHub Copilot SDK. ```bash npm install @github/copilot-sdk ``` -------------------------------- ### CommonJS package.json Example Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/examples/nodejs/langchain-js-setup.md Example package.json for a CommonJS project using LangChain and Azure Monitor. Ensure '@azure/monitor-opentelemetry' is installed. ```json { "name": "langchain-azure-monitor-demo", "version": "1.0.0", "main": "index.js", "scripts": { "start": "node index.js" }, "dependencies": { "@azure/monitor-opentelemetry": "^1.0.0", "@langchain/core": "^0.2.0", "@langchain/openai": "^0.2.0", "dotenv": "^16.0.0" } } ``` -------------------------------- ### Get Specific MCP Workload Details Source: https://github.com/microsoft/mcp/blob/main/servers/Fabric.Mcp.Server/TROUBLESHOOTING.md Retrieve detailed information about a specific MCP workload, such as its OpenAPI specification or examples. Use 'notebook' as an example workload type. ```bash dotnet run --project servers/Fabric.Mcp.Server/src/Fabric.Mcp.Server.csproj -- publicapis get --workload-type notebook ``` -------------------------------- ### Command Hierarchy Example Source: https://github.com/microsoft/mcp/blob/main/servers/Azure.Mcp.Server/docs/new-command.md Shows the layered hierarchy for command implementation, starting from IBaseCommand down to resource-specific commands. ```csharp IBaseCommand └── BaseCommand └── GlobalCommand └── SubscriptionCommand └── Service-specific base commands (e.g., BaseSqlCommand) └── Resource-specific commands (e.g., SqlIndexRecommendCommand) ``` -------------------------------- ### Basic Setup with TelemetryConfigurationBuilder Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/api-reference/dotnet/TelemetryConfigurationBuilder.md Demonstrates the basic setup pattern for TelemetryConfigurationBuilder, including setting the connection string and configuring custom trace and log processors, as well as resource attributes. ```csharp using Microsoft.ApplicationInsights.Extensibility; using OpenTelemetry; using OpenTelemetry.Trace; using OpenTelemetry.Logs; using OpenTelemetry.Resources; var config = TelemetryConfiguration.CreateDefault(); config.ConnectionString = "InstrumentationKey=...;IngestionEndpoint=..."; config.ConfigureOpenTelemetryBuilder(otel => { // Add custom trace processors otel.WithTracing(tracing => { tracing.AddProcessor(); tracing.AddProcessor(); }); // Add custom log processors otel.WithLogging(logging => { logging.AddProcessor(); }); // Set resource attributes (Cloud.RoleName, etc.) otel.ConfigureResource(r => r.AddService( serviceName: "MyWebApp", serviceInstanceId: Environment.MachineName, serviceVersion: "1.0.0")); }); ``` -------------------------------- ### Setup with OTLP Exporter Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/api-reference/dotnet/OtlpExporter.md Demonstrates how to configure the OTLP exporter for traces, metrics, and logs using dependency injection in C#. ```APIDOC ## Setup ```csharp using OpenTelemetry.Trace; using OpenTelemetry.Metrics; using OpenTelemetry.Logs; using OpenTelemetry.Exporter; // Azure Monitor is already configured via AddApplicationInsightsTelemetry. // Add OTLP as a secondary exporter: builder.Services.ConfigureOpenTelemetryTracerProvider(tracing => tracing.AddOtlpExporter(options => { options.Endpoint = new Uri("http://localhost:4317"); options.Protocol = OtlpExportProtocol.Grpc; })); builder.Services.ConfigureOpenTelemetryMeterProvider(metrics => metrics.AddOtlpExporter(options => { options.Endpoint = new Uri("http://localhost:4317"); })); builder.Services.ConfigureOpenTelemetryLoggerProvider(logging => logging.AddOtlpExporter(options => { options.Endpoint = new Uri("http://localhost:4317"); })); ``` .WithTracing(tracing => tracing.AddOtlpExporter()) .WithMetrics(metrics => metrics.AddOtlpExporter()); ``` ``` -------------------------------- ### Run Azure MCP Command without Installation (NPM) Source: https://github.com/microsoft/mcp/blob/main/servers/Azure.Mcp.Server/README.md Executes an Azure MCP command using npx without a prior installation. Replace '[command]' with the desired command, e.g., 'server start' or 'tools list'. ```bash npx -y @azure/mcp@latest [command] ``` ```bash npx -y @azure/mcp@latest server start ``` ```bash npx -y @azure/mcp@latest tools list ``` -------------------------------- ### Full Multi-Signal OpenTelemetrySdk.Create() Example Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/api-reference/dotnet/OpenTelemetrySdkCreate.md A comprehensive example showcasing the initialization of OpenTelemetrySdk with tracing, metrics, and logging, all configured to use OTLP exporters. This snippet is ideal for non-hosted applications that need to send all signals to an OpenTelemetry collector or backend. ```csharp using System.Diagnostics; using System.Diagnostics.Metrics; using Microsoft.Extensions.Logging; using OpenTelemetry; using OpenTelemetry.Logs; using OpenTelemetry.Metrics; using OpenTelemetry.Trace; var activitySource = new ActivitySource("MyApp"); var meter = new Meter("MyApp"); var requestCounter = meter.CreateCounter("requests"); using var sdk = OpenTelemetrySdk.Create(builder => builder .ConfigureResource(r => r.AddService("my-console-app")) .WithTracing(tracing => tracing .AddSource("MyApp") .AddOtlpExporter()) .WithMetrics(metrics => metrics .AddMeter("MyApp") .AddOtlpExporter()) .WithLogging(logging => logging .AddOtlpExporter())); var logger = sdk.GetLoggerFactory().CreateLogger(); using (var activity = activitySource.StartActivity("ProcessRequest")) { requestCounter.Add(1); logger.LogInformation("Request processed"); } // sdk.Dispose() flushes and shuts down all three providers. ``` -------------------------------- ### Test MCP Server Startup and Help Source: https://github.com/microsoft/mcp/blob/main/servers/Fabric.Mcp.Server/TROUBLESHOOTING.md Run the MCP server project to test its startup and view available command-line arguments, including help information. ```bash dotnet run --project servers/Fabric.Mcp.Server/src/Fabric.Mcp.Server.csproj -- --help ``` -------------------------------- ### Minimal Example Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/api-reference/dotnet/UseAzureMonitorExporter.md A basic example demonstrating how to add the Azure Monitor exporter to an ASP.NET Core application using minimal configuration, relying on environment variables for connection string. ```APIDOC ## Minimal Example ### Description This example shows the simplest way to integrate Azure Monitor export into an ASP.NET Core application. It assumes the `APPLICATIONINSIGHTS_CONNECTION_STRING` environment variable is set, and uses the default configuration for the exporter. ### Code ```csharp using Azure.Monitor.OpenTelemetry.Exporter; var builder = WebApplication.CreateBuilder(args); // Connection string from APPLICATIONINSIGHTS_CONNECTION_STRING env var builder.Services.AddOpenTelemetry().UseAzureMonitorExporter(); var app = builder.Build(); app.Run(); ``` ``` -------------------------------- ### 2.x ILogger Configuration with Application Insights Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/migration/dotnet/ilogger-migration.md In 2.x, explicit configuration of ILogger capture using AddApplicationInsights and category-specific filters targeting ApplicationInsightsLoggerProvider was common. This example shows the setup before migration. ```csharp using Microsoft.Extensions.Logging.ApplicationInsights; builder.Services.AddLogging(loggingBuilder => { loggingBuilder.AddApplicationInsights(options => { options.TrackExceptionsAsExceptionTelemetry = true; options.IncludeScopes = true; }); loggingBuilder.AddFilter("Microsoft.AspNetCore", LogLevel.Warning); loggingBuilder.AddFilter("MyApp", LogLevel.Information); }); ``` -------------------------------- ### Minimal OpenTelemetrySdk.Create() Example Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/api-reference/dotnet/OpenTelemetrySdkCreate.md This is a basic example demonstrating how to initialize OpenTelemetrySdk with tracing and metrics, configuring a service name and console exporters. It's suitable for non-hosted applications needing multiple signals. ```csharp using OpenTelemetry; using var sdk = OpenTelemetrySdk.Create(builder => builder .ConfigureResource(r => r.AddService("my-console-app")) .WithTracing(tracing => tracing .AddSource("MyApp") .AddConsoleExporter()) .WithMetrics(metrics => metrics .AddMeter("MyApp") .AddConsoleExporter())); // Application logic goes here. // sdk.Dispose() is called by `using`, which flushes all signals. ``` -------------------------------- ### Complete Flask Application with Azure Monitor Setup Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/examples/python/flask-setup.md A comprehensive example integrating Azure Monitor configuration, logging, custom spans, and error handling within a Flask application. ```python # app.py import os import logging from dotenv import load_dotenv # Load environment variables first load_dotenv() # Configure Azure Monitor BEFORE importing Flask from azure.monitor.opentelemetry import configure_azure_monitor configure_azure_monitor() # Now import Flask and other dependencies from flask import Flask, jsonify, request from opentelemetry import trace # Setup logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Create Flask app app = Flask(__name__) tracer = trace.get_tracer(__name__) @app.route('/') def index(): logger.info("Index page accessed") return jsonify({"status": "healthy"}) @app.route('/api/items') def list_items(): with tracer.start_as_current_span("list-items") as span: items = [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}] span.set_attribute("items.count", len(items)) return jsonify(items) @app.errorhandler(Exception) def handle_error(error): logger.error(f"Unhandled error: {error}") return jsonify({"error": "Internal server error"}), 500 if __name__ == '__main__': app.run(host='0.0.0.0', port=5000) ``` -------------------------------- ### Full Worker Service Setup with Options Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/api-reference/dotnet/AddApplicationInsightsTelemetryWorkerService.md An example of configuring Application Insights telemetry with specific options, such as connection string and sampling ratio, using an inline options delegate. ```csharp using Microsoft.Extensions.DependencyInjection; using Microsoft.ApplicationInsights.WorkerService; var builder = Host.CreateDefaultBuilder(args); builder.ConfigureServices(services => { services.AddApplicationInsightsTelemetryWorkerService(options => { options.ConnectionString = "InstrumentationKey=...;IngestionEndpoint=..."; options.EnableQuickPulseMetricStream = true; options.SamplingRatio = 0.5f; // Collect 50% of telemetry }); }); var host = builder.Build(); await host.RunAsync(); ``` -------------------------------- ### Setup Multi-Service Project Structure Source: https://github.com/microsoft/mcp/blob/main/docs/bug-bash/scenarios/deployment.md Creates a project directory structure for a multi-service application, including separate directories for frontend and backend, and initializes package.json files. ```bash # Create multi-service project mkdir bugbash-fullstack && cd bugbash-fullstack mkdir frontend backend # Frontend (React app - simplified) cat > frontend/package.json << 'EOF' { "name": "frontend", "version": "1.0.0", "scripts": { "build": "echo 'Building React app'" } } EOF # Backend (Node.js API) cat > backend/package.json << 'EOF' { "name": "backend", "version": "1.0.0", "main": "server.js", "scripts": { "start": "node server.js" }, "dependencies": { "express": "^4.18.0" } } EOF cat > backend/server.js << 'EOF' const express = require('express'); const app = express(); app.get('/api/health', (req, res) => res.json({ status: 'healthy' })); app.listen(process.env.PORT || 8080); EOF ``` -------------------------------- ### Python Example: Configure and Use Azure MCP with Copilot SDK Source: https://github.com/microsoft/mcp/blob/main/servers/Azure.Mcp.Server/README.md This Python script demonstrates initializing the Copilot client, configuring an Azure MCP server, creating a session, and sending a prompt to list Azure resource groups. ```python import asyncio from copilot import CopilotClient from copilot.generated.session_events import SessionEventType async def main(): # Initialize the Copilot client client = CopilotClient({ "cli_args": [ "--allow-all-tools", "--allow-all-paths", ] }) await client.start() # Configure Azure MCP server in session config azure_mcp_config = { "azure-mcp": { "type": "local", "command": "npx", "args": ["-y", "@azure/mcp@latest", "server", "start"], "tools": ["*"], # Enable all Azure MCP tools } } # Create session with MCP servers session = await client.create_session({ "model": "gpt-4.1", # Default model; BYOK can override "streaming": True, "mcp_servers": azure_mcp_config, }) # Handle events def handle_event(event): if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA: if hasattr(event.data, 'delta_content') and event.data.delta_content: print(event.data.delta_content, end="", flush=True) elif event.type == SessionEventType.TOOL_EXECUTION_START: tool_name = getattr(event.data, 'tool_name', 'unknown') print(f"\n[TOOL: {tool_name}]") session.on(handle_event) # Send prompt await session.send_and_wait({ "prompt": "List all resource groups in my Azure subscription" }) await client.stop() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize Project with Template and Environment Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Extension/src/Resources/azd-best-practices.txt Scaffolds a new project from a specified template and sets the environment name. Ensure the `cwd` parameter points to the project's absolute path. ```bash azd init --template todo-node ``` -------------------------------- ### VS Code MCP Extension Verification Steps Source: https://github.com/microsoft/mcp/blob/main/docs/bug-bash/installation-testing.md Provides steps to verify the installation of the Azure MCP Server extension in VS Code by checking its presence, starting the server, and reviewing logs. ```plaintext 1. Open Command Palette (Ctrl+Shift+P / Cmd+Shift+P) 2. Run "MCP: List Servers" 3. Verify "Azure MCP Server" appears in the list 4. Click "Start Server" 5. Check Output window for startup logs ``` -------------------------------- ### Example: Azure US Government with Environment Variable and PowerShell Authentication Source: https://github.com/microsoft/mcp/blob/main/docs/sovereign-clouds.md Shows setting the AZURE_CLOUD environment variable for Azure US Government, authenticating with Azure PowerShell, and starting the MCP server. ```powershell # Set environment variable $env:AZURE_CLOUD = "AzureUSGovernment" # Authenticate with PowerShell Connect-AzAccount -Environment AzureUSGovernment # Start the MCP server (will use AZURE_CLOUD env var) azmcp server start ``` -------------------------------- ### Quick Start Scenario: Resource Discovery Prompts Source: https://github.com/microsoft/mcp/blob/main/docs/bug-bash/README.md Utilize these prompts in the 'Resource Discovery' quick start scenario to list various Azure resources. ```plaintext List all storage accounts in my subscription ``` ```plaintext Show me my Key Vaults ``` ```plaintext List all App Services in resource group ``` -------------------------------- ### Create and Use a Counter for Metrics Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/concepts/python/opentelemetry-pipeline.md This example demonstrates how to get a meter, create a counter, and record metric data with attributes. Use counters to track the number of occurrences of an event, such as incoming requests. ```python from opentelemetry import metrics meter = metrics.get_meter(__name__) request_counter = meter.create_counter("requests") request_counter.add(1, {"endpoint": "/api/users"}) ``` -------------------------------- ### Minimal Worker Service Setup Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/api-reference/dotnet/AddApplicationInsightsTelemetryWorkerService.md A basic example of setting up Application Insights telemetry for a .NET Worker Service using the parameterless overload. Configuration is expected to be provided via environment variables or appsettings.json. ```csharp using Microsoft.Extensions.DependencyInjection; var builder = Host.CreateDefaultBuilder(args); builder.ConfigureServices(services => { services.AddApplicationInsightsTelemetryWorkerService(); }); var host = builder.Build(); await host.RunAsync(); ``` -------------------------------- ### Complete FastAPI Application with Azure Monitor Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/examples/python/fastapi-setup.md A full example of a FastAPI application integrating Azure Monitor, including environment variable loading, Azure Monitor configuration, logging setup, and basic API endpoints. ```python # main.py import os import logging from dotenv import load_dotenv # Load environment variables first load_dotenv() # Configure Azure Monitor BEFORE importing FastAPI from azure.monitor.opentelemetry import configure_azure_monitor configure_azure_monitor() # Now import FastAPI and other dependencies from fastapi import FastAPI, HTTPException, Request from pydantic import BaseModel from opentelemetry import trace # Setup logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) ``` -------------------------------- ### Provision Test Resources on Desktop Source: https://github.com/microsoft/mcp/blob/main/eng/common/TestResources/New-TestResources.ps1.md Use this example to provision test resources on a local desktop environment. It specifies details for the resource group, subscription, and application principals. ```powershell New-TestResources.ps1 \ -BaseName 'azsdk' \ -ServiceDirectory 'keyvault' \ -SubscriptionId 'REPLACE_WITH_SUBSCRIPTION_ID' \ -ResourceGroupName 'REPLACE_WITH_NAME_FOR_RESOURCE_GROUP' \ -Location 'eastus' \ -ProvisionerApplicationId 'REPLACE_WITH_PROVISIONER_APPLICATION_ID' \ -ProvisionerApplicationSecret 'REPLACE_WITH_PROVISIONER_APPLICATION_ID' \ -TestApplicationId 'REPLACE_WITH_TEST_APPLICATION_ID' \ -TestApplicationOid 'REPLACE_WITH_TEST_APPLICATION_OBJECT_ID' \ -TestApplicationSecret 'REPLACE_WITH_TEST_APPLICATION_SECRET' ``` -------------------------------- ### Minimal Application Insights Setup Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/api-reference/dotnet/AddApplicationInsightsTelemetry.md A minimal example demonstrating how to add Application Insights telemetry to a .NET Core application using the parameterless overload. The connection string should be set via environment variable or appsettings.json. ```csharp using Microsoft.Extensions.DependencyInjection; var builder = WebApplication.CreateBuilder(args); builder.Services.AddApplicationInsightsTelemetry(); var app = builder.Build(); ``` ```bash APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=...;IngestionEndpoint=... ``` ```json { "ApplicationInsights": { "ConnectionString": "InstrumentationKey=...;IngestionEndpoint=..." } } ``` -------------------------------- ### Configure Metrics with Advanced Options Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/api-reference/dotnet/WithMetrics.md This example demonstrates enabling metrics with advanced configuration options, including setting a service resource, subscribing to multiple meters, adding instrumentation for ASP.NET Core and HttpClient, configuring custom views for request duration, setting a maximum stream limit, and configuring exemplar filters. It also includes OTLP export. ```csharp using OpenTelemetry; using OpenTelemetry.Metrics; using OpenTelemetry.Resources; var builder = WebApplication.CreateBuilder(args); builder.Services.AddOpenTelemetry() .ConfigureResource(r => r.AddService("order-api")) .WithMetrics(metrics => metrics .AddMeter("OrderService", "PaymentService") .AddAspNetCoreInstrumentation() .AddHttpClientInstrumentation() .AddView("request-duration", new ExplicitBucketHistogramConfiguration { Boundaries = new double[] { 0.01, 0.05, 0.1, 0.5, 1, 5, 10 } }) .SetMaxMetricStreams(500) .SetExemplarFilter(ExemplarFilterType.TraceBased) .AddOtlpExporter()); var app = builder.Build(); app.Run(); ``` -------------------------------- ### Manual Instrumentation with Custom Spans Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.Monitor/src/Instrumentation/Resources/concepts/nodejs/opentelemetry-pipeline.md Demonstrates how to manually create custom spans for detailed tracing within your Node.js application. This snippet shows how to get a tracer, start and end a span, add attributes and events, and record exceptions. ```javascript const { trace } = require('@opentelemetry/api'); // Get tracer const tracer = trace.getTracer('my-app'); // Create custom span const span = tracer.startSpan('process-data'); try { // Your business logic span.setAttribute('record.count', 100); span.addEvent('Processing started'); // ... do work ... span.addEvent('Processing completed'); } catch (error) { span.recordException(error); span.setStatus({ code: SpanStatusCode.ERROR }); } finally { span.end(); } ``` -------------------------------- ### Initialize and Configure Azure MCP Server in Go Source: https://github.com/microsoft/mcp/blob/main/servers/Azure.Mcp.Server/README.md Initializes the Copilot client, configures the Azure MCP server, creates a session, and sends a prompt. Ensure the Copilot SDK for Go is installed. ```go package main import ( "context" "fmt" "log" copilot "github.com/github/copilot-sdk/go" ) func main() { ctx := context.Background() // Initialize the Copilot client client, err := copilot.NewClient(copilot.ClientOptions{ CLIArgs: []string{ "--allow-all-tools", "--allow-all-paths", }, }) if err != nil { log.Fatal(err) } if err := client.Start(ctx); err != nil { log.Fatal(err) } defer client.Stop(ctx) // Configure Azure MCP server in session config azureMcpConfig := map[string]copilot.MCPServerConfig{ "azure-mcp": { Type: "local", Command: "npx", Args: []string{" -y", "@azure/mcp@latest", "server", "start"}, Tools: []string{"*"}, // Enable all Azure MCP tools }, } // Create session with MCP servers session, err := client.CreateSession(ctx, copilot.SessionConfig{ Model: "gpt-4.1", // Default model; BYOK can override Streaming: true, MCPServers: azureMcpConfig, }) if err != nil { log.Fatal(err) } // Handle events session.OnEvent(func(event copilot.SessionEvent) { switch event.Type { case copilot.AssistantMessageDelta: if event.Data.DeltaContent != "" { fmt.Print(event.Data.DeltaContent) } case copilot.ToolExecutionStart: fmt.Printf("\n[TOOL: %s]\n", event.Data.ToolName) } }) // Send prompt err = session.SendAndWait(ctx, copilot.Message{ Prompt: "List all resource groups in my Azure subscription", }) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Start Azure MCP Server with Configuration File (.NET Tool) Source: https://github.com/microsoft/mcp/blob/main/docs/bug-bash/installation-testing.md Starts the Azure MCP server using a specified JSON configuration file. CLI flags can override settings from the file. ```bash azmcp server start --config azmcp.config.json ``` -------------------------------- ### Check Node.js Installation (macOS) Source: https://github.com/microsoft/mcp/blob/main/docs/bug-bash/installation-testing.md Verifies if Node.js is installed on macOS. If not, it suggests installing it via Homebrew. ```bash # Check if Node.js is installed node --version # Install via Homebrew if needed brew install node ``` -------------------------------- ### Install Copilot SDK for .NET Source: https://github.com/microsoft/mcp/blob/main/servers/Azure.Mcp.Server/README.md Installs the Copilot SDK for .NET using the dotnet add package command. This is a prerequisite for using the .NET client. ```bash dotnet add package GitHub.Copilot.SDK ``` -------------------------------- ### Install Azure MCP via NPM (Local) Source: https://github.com/microsoft/mcp/blob/main/servers/Azure.Mcp.Server/README.md Installs the @azure/mcp Node.js package locally within your project. This is the recommended installation method. ```bash npm install @azure/mcp@latest ``` ```bash npm install @azure/mcp@ ``` -------------------------------- ### Build the Server Source: https://github.com/microsoft/mcp/blob/main/CONTRIBUTING.md Compile the entire project from the root directory. This command is a prerequisite for running the server locally. ```bash dotnet build ``` -------------------------------- ### Install Azure MCP .NET Tool Source: https://github.com/microsoft/mcp/blob/main/docs/bug-bash/installation-testing.md Installs the Azure MCP .NET tool globally using the 'dotnet tool install' command. ```bash dotnet tool install --global Azure.Mcp ``` -------------------------------- ### Verify Azure MCP Installation (Windows) Source: https://github.com/microsoft/mcp/blob/main/docs/bug-bash/installation-testing.md Checks the installed Azure MCP version, verifies the Azure CLI installation, and tests a basic command. ```powershell # Check Azure MCP version azmcp --version # Verify Azure CLI az --version # Test basic command azmcp server start --help ``` -------------------------------- ### Install Azure MCP via NuGet (Windows) Source: https://github.com/microsoft/mcp/blob/main/docs/bug-bash/installation-testing.md Installs the Azure MCP .NET tool using the `dotnet tool install` command on a Windows system. ```powershell dotnet tool install Azure.Mcp ``` -------------------------------- ### Unit Testing CancellationToken Mock Setup and Invocation Source: https://github.com/microsoft/mcp/blob/main/servers/Azure.Mcp.Server/docs/new-command.md Illustrates how to set up mocks for CancellationToken parameters using `Arg.Any()` and how to invoke product code with `TestContext.Current.CancellationToken` in unit tests. ```csharp // Mock setup in unit tests Service.GetResourceAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(mockResource); // Invoking product code in unit tests var result = await Service.GetResourceAsync( "test-resource", "test-subscription", "test-rg", null, TestContext.Current.CancellationToken); ``` -------------------------------- ### Manual Start MCP Server in VS Code Source: https://github.com/microsoft/mcp/blob/main/servers/Fabric.Mcp.Server/README.md Manually start the Fabric MCP Server if autostart is disabled. Use the Command Palette to list and start servers. ```plaintext 1. Open Command Palette (`Ctrl+Shift+P` / `Cmd+Shift+P`). 2. Run `MCP: List Servers`. 3. Select `Fabric MCP Server`, then click **Start Server**. ``` -------------------------------- ### Initialize Azure Static Web Apps Project with azd Source: https://github.com/microsoft/mcp/blob/main/tools/Azure.Mcp.Tools.AzureBestPractices/src/Resources/azure-swa-best-practices.txt Use `azd init` to set up a new Azure Static Web Apps project. This command should only be used for new projects. ```bash # Initialize (if not already) azd init ```