### Run Basic Usage Example with ts-node Source: https://github.com/shinzo-labs/shinzo-ts/blob/main/examples/README.md This command demonstrates how to run the basic usage example of the MCP server using ts-node. It requires navigating to the examples directory first. ```bash cd packages/instrumentation-mcp/examples npx ts-node basic-usage.ts ``` -------------------------------- ### Test Utilities Example (TypeScript) Source: https://github.com/shinzo-labs/shinzo-ts/blob/main/test/README.md Provides examples of using utility functions from the test setup file, such as waiting for asynchronous operations, advancing timers, and creating asynchronous mocks. These utilities aid in managing test timing and mock behavior. ```typescript import { testUtils } from './setup'; // Wait for async operations await testUtils.waitForNextTick(); // Advance timers await testUtils.waitFor(1000); // Create async mocks const mockFn = testUtils.createAsyncMock('resolved value'); ``` -------------------------------- ### Configure Claude Desktop MCP Server Source: https://github.com/shinzo-labs/shinzo-ts/blob/main/examples/README.md This JSON configuration shows how to set up a basic MCP server within Claude Desktop. It specifies the command to run the example, arguments, and environment variables for telemetry configuration. ```json { "mcpServers": { "shinzo-basic-example": { "command": "npx", "args": ["ts-node", "/path/to/shinzo/packages/instrumentation-mcp/examples/basic-usage.ts"], "env": { "OTEL_EXPORTER_OTLP_ENDPOINT": "http://localhost:4318/v1", "OTEL_AUTH_TOKEN": "my-auth-token" } } } } ``` -------------------------------- ### Install Shinzo MCP Instrumentation SDK Source: https://github.com/shinzo-labs/shinzo-ts/blob/main/README.md Installs the Shinzo instrumentation SDK for MCP servers using pnpm. This package provides the necessary tools to instrument your server for observability. ```bash pnpm add @shinzolabs/instrumentation-mcp ``` -------------------------------- ### Basic MCP Server Instrumentation with Shinzo TypeScript SDK Source: https://github.com/shinzo-labs/shinzo-ts/blob/main/README.md Demonstrates the basic setup for instrumenting an MCP server using the Shinzo TypeScript SDK. It requires server name, version, and the OpenTelemetry collector endpoint. ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" import { instrumentServer, TelemetryConfig } from "@shinzolabs/instrumentation-mcp" const NAME = "my-mcp-server" const VERSION = "1.0.0" const server = new McpServer({ name: NAME, version: VERSION, description: "Example MCP server with telemetry" }) // Use TelemetryConfig to set configuration options const telemetryConfig: TelemetryConfig = { serverName: NAME, serverVersion: VERSION, exporterEndpoint: "http://localhost:4318/v1" // OpenTelemetry collector endpoint - /trace and /metrics are added automatically } // Initialize telemetry const telemetry = instrumentServer(server, telemetryConfig) // Add tools using the tool method server.tool(...) ``` -------------------------------- ### Console Telemetry Setup for Development Source: https://github.com/shinzo-labs/shinzo-ts/blob/main/README.md Configures telemetry for development using the console exporter. Metrics are disabled as the console exporter does not support them. All traces are sampled. ```typescript const telemetryConfig: TelemetryConfig = { serverName: "my-server", serverVersion: "1.0.0", exporterType: "console", enableMetrics: false, // Console exporter doesn't support metrics samplingRate: 1.0 // Sample all traces in development } ``` -------------------------------- ### Telemetry Configuration with Custom Data Processors Source: https://github.com/shinzo-labs/shinzo-ts/blob/main/README.md Demonstrates how to use custom data processors to modify telemetry data before it's exported. This example removes sensitive parameters for a specific tool. ```typescript const telemetryConfig: TelemetryConfig = { serverName: "my-server", serverVersion: "1.0.0", exporterEndpoint: "http://localhost:4318/v1", // OpenTelemetry collector endpoint dataProcessors: [ (data) => { // Remove sensitive parameters if (data['mcp.tool.name'] === 'sensitive_tool') { delete data['mcp.request.argument.password'] } return data } ] } ``` -------------------------------- ### Create a Changeset using pnpm Source: https://github.com/shinzo-labs/shinzo-ts/blob/main/CONTRIBUTING.md This command initiates the process of creating a changeset file, which is used to manage versioning and publishing of packages in the monorepo. It guides the user through selecting affected packages, choosing a version bump type, and describing the changes. ```bash pnpm changeset ``` -------------------------------- ### Record Custom Metrics with Shinzo Instrumentation MCP (TypeScript) Source: https://context7.com/shinzo-labs/shinzo-ts/llms.txt This snippet demonstrates how to record custom histogram and counter metrics for application-specific measurements using the @shinzolabs/instrumentation-mcp library. It includes setup for a telemetry server, defining histogram and counter instruments, and associating metric recording with a server tool. ```typescript import { instrumentServer, TelemetryConfig } from "@shinzolabs/instrumentation-mcp" import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" const server = new McpServer({ name: "metrics-server", version: "1.0.0" }) const telemetryConfig: TelemetryConfig = { serverName: "metrics-server", serverVersion: "1.0.0", exporterEndpoint: "http://localhost:4318/v1", enableMetrics: true, metricExportIntervalMs: 5000 } const telemetry = instrumentServer(server, telemetryConfig) // Create histogram for tracking data size const recordDataSize = telemetry.getHistogram('app.data.size', { description: 'Size of data processed in bytes', unit: 'bytes' }) // Create counter for tracking cache hits const incrementCacheHits = telemetry.getIncrementCounter('app.cache.hits', { description: 'Number of cache hits', unit: 'hits' }) server.tool("process_data", "Processes data with caching", { input: z.string() }, async (params) => { const dataSize = Buffer.byteLength(params.input, 'utf8') recordDataSize(dataSize, { 'data.type': 'string', 'processing.method': 'sync' }) const cacheKey = `cache:${params.input}` const cached = checkCache(cacheKey) if (cached) { incrementCacheHits(1, { 'cache.type': 'memory', 'cache.hit': true }) return { content: [{ type: "text", text: `Cached result: ${cached}` }] } } const result = processData(params.input) storeCache(cacheKey, result) return { content: [{ type: "text", text: `Processed: ${result}` }] } } ) function checkCache(key: string): string | null { // Simulated cache lookup return null } function storeCache(key: string, value: string): void { // Simulated cache storage } function processData(input: string): string { return input.toUpperCase() } ``` -------------------------------- ### Mock MCP Server Usage (TypeScript) Source: https://github.com/shinzo-labs/shinzo-ts/blob/main/test/README.md Demonstrates how to import and use the MockMcpServer class and its associated test tools for creating mock server instances and calling tools within tests. This is useful for simulating server interactions during testing. ```typescript import { MockMcpServer, createTestTools } from './mocks/MockMcpServer'; // Create mock server const server = new MockMcpServer(); // Add test tools createTestTools(server); // Use in tests await server.callTool('calculator', { operation: 'add', a: 1, b: 2 }); ``` -------------------------------- ### Running All Tests (Bash) Source: https://github.com/shinzo-labs/shinzo-ts/blob/main/test/README.md Basic bash commands for running the test suite. These commands cover executing all tests, running tests with coverage, and entering watch mode for iterative development. ```bash # Run all tests pnpm test # Run tests with coverage pnpm test:coverage # Run tests in watch mode pnpm test:watch ``` -------------------------------- ### Advanced MCP Server Instrumentation with Shinzo TypeScript SDK Source: https://github.com/shinzo-labs/shinzo-ts/blob/main/README.md Illustrates advanced configuration options for instrumenting an MCP server with the Shinzo TypeScript SDK. This includes authentication, PII sanitization, tracing control, sampling rates, and custom data processors. ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" import { instrumentServer, TelemetryConfig } from "@shinzolabs/instrumentation-mcp" const NAME = "my-other-mcp-server" const VERSION = "1.0.0" const server = new McpServer({ name: NAME, version: VERSION, description: "Example MCP server with telemetry" }) const telemetryConfig: TelemetryConfig = { serviceName: NAME, serviceVersion: VERSION, exporterEndpoint: "http://localhost:4318/v1", // OpenTelemetry collector endpoint exporterAuth: { type: "bearer", token: process.env.OTEL_AUTH_TOKEN }, enablePIISanitization: false, enableTracing: false, samplingRate: 0.7, dataProcessors: [ (telemetryData: any) => { if (telemetryData['mcp.tool.name'] === "sensitive_operation") { for (const key of Object.keys(telemetryData)) { if (key.startsWith('mcp.request.argument')) delete telemetryData[key] } } return telemetryData } ] } const telemetry = instrumentServer(server, telemetryConfig) // Add tools using the tool method server.tool(...) ``` -------------------------------- ### Minimal Telemetry Configuration Source: https://github.com/shinzo-labs/shinzo-ts/blob/main/README.md Sets up the basic telemetry configuration with server name, version, and the OpenTelemetry collector endpoint. ```typescript const telemetryConfig: TelemetryConfig = { serverName: "my-server", serverVersion: "1.0.0", exporterEndpoint: "http://localhost:4318/v1" // OpenTelemetry collector endpoint } ``` -------------------------------- ### Advanced Test Execution Options (Bash) Source: https://github.com/shinzo-labs/shinzo-ts/blob/main/test/README.md Advanced bash commands for controlling test execution, including running specific test files, filtering tests by name pattern, enabling verbose output, and viewing coverage reports. ```bash # Run specific test file pnpm test config.test.ts # Run tests matching a pattern pnpm test --testNamePattern="sanitize" # Run tests with verbose output pnpm test --verbose # Run tests with coverage and open report pnpm test:coverage && open coverage/lcov-report/index.html # View coverage report in terminal pnpm test:coverage --verbose ``` -------------------------------- ### Telemetry Configuration with Authentication Options Source: https://context7.com/shinzo-labs/shinzo-ts/llms.txt Demonstrates configuring telemetry exporters with various authentication methods, including bearer tokens, API keys, and basic authentication. This allows secure and flexible connection to telemetry backends. Requires `@shinzolabs/instrumentation-mcp` and `@modelcontextprotocol/sdk/server/mcp.js`. ```typescript import { instrumentServer, TelemetryConfig } from "@shinzolabs/instrumentation-mcp" import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" const server = new McpServer({ name: "authenticated-server", version: "2.0.0" }) // Bearer token authentication const bearerConfig: TelemetryConfig = { serverName: "authenticated-server", serverVersion: "2.0.0", exporterEndpoint: "https://api.shinzo.ai/v1", exporterAuth: { type: "bearer", token: process.env.SHINZO_TOKEN } } // API key authentication const apiKeyConfig: TelemetryConfig = { serverName: "authenticated-server", serverVersion: "2.0.0", exporterEndpoint: "https://api.example.com/v1", exporterAuth: { type: "apiKey", apiKey: process.env.API_KEY } } // Basic authentication const basicConfig: TelemetryConfig = { serverName: "authenticated-server", serverVersion: "2.0.0", exporterEndpoint: "https://api.example.com/v1", exporterAuth: { type: "basic", username: process.env.USERNAME, password: process.env.PASSWORD } } const telemetry = instrumentServer(server, bearerConfig) ``` -------------------------------- ### Configure Trace Sampling for Production and Staging Source: https://context7.com/shinzo-labs/shinzo-ts/llms.txt This snippet demonstrates how to configure trace sampling rates for different environments (production, staging, development) using the Shinzo TS SDK. It adjusts the sampling rate via the TelemetryConfig to control telemetry volume in high-traffic environments. Dependencies include `@shinzolabs/instrumentation-mcp` and `@modelcontextprotocol/sdk/server/mcp.js`. ```typescript import { instrumentServer, TelemetryConfig } from "@shinzolabs/instrumentation-mcp" import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" const server = new McpServer({ name: "sampled-server", version: "1.0.0" }) // Production configuration with 10% sampling const productionConfig: TelemetryConfig = { serverName: "sampled-server", serverVersion: "1.0.0", exporterEndpoint: "https://otel-collector.production.example.com/v1", exporterAuth: { type: "bearer", token: process.env.PROD_OTEL_TOKEN }, samplingRate: 0.1, // Sample 10% of traces enableMetrics: true, enableTracing: true, metricExportIntervalMs: 10000, batchTimeoutMs: 5000 } // Staging configuration with 50% sampling const stagingConfig: TelemetryConfig = { serverName: "sampled-server", serverVersion: "1.0.0", exporterEndpoint: "https://otel-collector.staging.example.com/v1", samplingRate: 0.5, // Sample 50% of traces enableMetrics: true, enableTracing: true } // Development configuration with 100% sampling const devConfig: TelemetryConfig = { serverName: "sampled-server", serverVersion: "1.0.0", exporterType: "console", samplingRate: 1.0, // Sample all traces enableMetrics: false } const config = process.env.NODE_ENV === 'production' ? productionConfig : process.env.NODE_ENV === 'staging' ? stagingConfig : devConfig const telemetry = instrumentServer(server, config) ``` -------------------------------- ### Running Specific Test Categories (Bash) Source: https://github.com/shinzo-labs/shinzo-ts/blob/main/test/README.md Bash commands to selectively run specific categories of tests, such as unit tests or integration tests. This allows developers to focus on a particular subset of tests during development. ```bash # Run only unit tests pnpm test:unit # Run only integration tests pnpm test:integration ``` -------------------------------- ### Sanitize PII with Shinzo Instrumentation MCP (TypeScript) Source: https://context7.com/shinzo-labs/shinzo-ts/llms.txt This snippet illustrates how to enable automatic PII sanitization for telemetry data using the @shinzolabs/instrumentation-mcp library. It shows the configuration for using the default PII sanitizer and how to implement a custom PII sanitizer by extending the base PIISanitizer class. ```typescript import { instrumentServer, TelemetryConfig, PIISanitizer } from "@shinzolabs/instrumentation-mcp" import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" const server = new McpServer({ name: "pii-protected-server", version: "1.0.0" }) // Use default PII sanitizer const defaultConfig: TelemetryConfig = { serverName: "pii-protected-server", serverVersion: "1.0.0", exporterEndpoint: "http://localhost:4318/v1", enablePIISanitization: true, // Enables default sanitizer enableArgumentCollection: true } // Use custom PII sanitizer class CustomPIISanitizer extends PIISanitizer { public sanitize(data: Record): Record { const sanitized = super.sanitize(data) // Call default sanitization // Add custom sanitization rules for (const key of Object.keys(sanitized)) { if (key.includes('user_id') || key.includes('customer_id')) { sanitized[key] = '[REDACTED_ID]' } if (typeof sanitized[key] === 'string' && sanitized[key].includes('private:')) { sanitized[key] = sanitized[key].replace(/private:.*$/g, 'private:[REDACTED]') } } return sanitized } } const customConfig: TelemetryConfig = { serverName: "pii-protected-server", serverVersion: "1.0.0", exporterEndpoint: "http://localhost:4318/v1", enablePIISanitization: true, PIISanitizer: new CustomPIISanitizer() } const telemetry = instrumentServer(server, customConfig) server.tool("user_lookup", "Looks up user information", { email: z.string().email(), ssn: z.string() }, async (params) => { // Email and SSN will be automatically redacted in telemetry // Output: email=[REDACTED], ssn=[REDACTED] const user = lookupUser(params.email, params.ssn) return { content: [{ type: "text", text: `User found: ${user.name}` }] } } ) function lookupUser(email: string, ssn: string): { name: string } { return { name: "John Doe" } } ``` -------------------------------- ### Create Manual Spans for Instrumentation in TypeScript Source: https://context7.com/shinzo-labs/shinzo-ts/llms.txt Enables manual creation of custom spans to instrument specific business logic or operations that are not automatically captured by the system. This allows for detailed tracking of performance and errors within critical code paths. It requires the `@shinzolabs/instrumentation-mcp` package, `McpServer`, and elements from `@opentelemetry/api`. ```typescript import { instrumentServer, TelemetryConfig } from "@shinzolabs/instrumentation-mcp" import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" import { SpanStatusCode } from "@opentelemetry/api" const server = new McpServer({ name: "manual-instrumentation-server", version: "1.0.0" }) const telemetryConfig: TelemetryConfig = { serverName: "manual-instrumentation-server", serverVersion: "1.0.0", exporterEndpoint: "http://localhost:4318/v1" } const telemetry = instrumentServer(server, telemetryConfig) server.tool("complex_operation", "Performs a complex multi-step operation", { data: z.string() }, async (params) => { // Manual span for a specific operation return telemetry.startActiveSpan( "database.query", { "db.system": "postgresql", "db.operation": "SELECT", "custom.query_complexity": "high" }, (span) => { try { // Simulate database operation const result = performDatabaseQuery(params.data) span.setStatus({ code: SpanStatusCode.OK }) span.setAttribute("db.rows_returned", result.length) return { content: [{ type: "text", text: `Found ${result.length} records` }] } } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }) span.setAttribute("error.type", error.name) throw error } finally { span.end() } } ) } ) function performDatabaseQuery(query: string): any[] { // Simulated database operation return [{ id: 1, data: query }] } ``` -------------------------------- ### Instrument MCP Server with Telemetry Source: https://context7.com/shinzo-labs/shinzo-ts/llms.txt Instruments an MCP server instance with OpenTelemetry tracing and metrics. It configures server details, exporter endpoint, authentication, sampling rate, and data collection options. The function returns an observability instance for manual instrumentation and lifecycle management. Requires `@modelcontextprotocol/sdk/server/mcp.js`, `@modelcontextprotocol/sdk/server/stdio.js`, and `@shinzolabs/instrumentation-mcp`. ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js" import { instrumentServer, TelemetryConfig } from "@shinzolabs/instrumentation-mcp" import { z } from "zod" const server = new McpServer({ name: "example-server", version: "1.0.0", description: "Example MCP server with telemetry" }) const telemetryConfig: TelemetryConfig = { serverName: "example-server", serverVersion: "1.0.0", exporterEndpoint: "http://localhost:4318/v1", exporterAuth: { type: "bearer", token: process.env.OTEL_AUTH_TOKEN }, samplingRate: 1.0, enableArgumentCollection: true, enablePIISanitization: true } const telemetry = instrumentServer(server, telemetryConfig) // Add tools - they will be automatically instrumented server.tool("calculate", "Performs a calculation", { operation: z.enum(["add", "subtract", "multiply", "divide"]), a: z.number(), b: z.number() }, async (params) => { let result: number switch (params.operation) { case "add": result = params.a + params.b; break case "subtract": result = params.a - params.b; break case "multiply": result = params.a * params.b; break case "divide": result = params.a / params.b; break } return { content: [{ type: "text", text: `Result: ${result}` }] } } ) process.on('SIGINT', async () => { await telemetry.shutdown() process.exit(0) }) async function main() { const transport = new StdioServerTransport() await server.connect(transport) } main().catch(console.error) ``` -------------------------------- ### Telemetry Configuration with Bearer Token Authentication Source: https://github.com/shinzo-labs/shinzo-ts/blob/main/README.md Configures telemetry with bearer token authentication, using an environment variable for the token. Requires `exporterAuth` to be set. ```typescript const telemetryConfig: TelemetryConfig = { serverName: "my-server", serverVersion: "1.0.0", exporterEndpoint: "https://api.example.com/v1", exporterAuth: { type: "bearer", token: process.env.OTEL_AUTH_TOKEN } } ``` -------------------------------- ### Configure Console Exporter for Development in TypeScript Source: https://context7.com/shinzo-labs/shinzo-ts/llms.txt Sets up telemetry to output directly to the console, useful for local development and debugging without needing an external collector. This configuration disables metrics export as the console exporter does not support them. It relies on the `@shinzolabs/instrumentation-mcp` package and `McpServer` from the SDK. ```typescript import { instrumentServer, TelemetryConfig } from "@shinzolabs/instrumentation-mcp" import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" const server = new McpServer({ name: "dev-server", version: "1.0.0" }) const devConfig: TelemetryConfig = { serverName: "dev-server", serverVersion: "1.0.0", exporterType: "console", enableMetrics: false, // Console exporter doesn't support metrics enableTracing: true, samplingRate: 1.0, // Sample all traces in development enableArgumentCollection: true, enablePIISanitization: false // Disable for easier debugging } const telemetry = instrumentServer(server, devConfig) // Tool calls will now log spans to console server.tool("hello", "Says hello", { name: z.string() }, async (params) => ({ content: [{ type: "text", text: `Hello, ${params.name}!` }] }) ) ``` -------------------------------- ### Implement Graceful Shutdown for Telemetry Source: https://context7.com/shinzo-labs/shinzo-ts/llms.txt This TypeScript code snippet illustrates how to implement graceful shutdown for telemetry in an MCP server. It ensures that all pending spans and metrics are flushed before the process terminates by handling SIGINT and SIGTERM signals, and using the `telemetry.shutdown()` method. Dependencies include `@shinzolabs/instrumentation-mcp`, `@modelcontextprotocol/sdk/server/mcp.js`, and `@modelcontextprotocol/sdk/server/stdio.js`. ```typescript import { instrumentServer, TelemetryConfig } from "@shinzolabs/instrumentation-mcp" import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js" const server = new McpServer({ name: "graceful-shutdown-server", version: "1.0.0" }) const telemetryConfig: TelemetryConfig = { serverName: "graceful-shutdown-server", serverVersion: "1.0.0", exporterEndpoint: "http://localhost:4318/v1", batchTimeoutMs: 2000 } const telemetry = instrumentServer(server, telemetryConfig) // Handle multiple shutdown signals const shutdownHandler = async (signal: string) => { console.log(`Received ${signal}, shutting down gracefully...`) try { // Shutdown telemetry first to flush pending data await telemetry.shutdown() console.log('Telemetry shutdown complete') // Then exit process process.exit(0) } catch (error) { console.error('Error during shutdown:', error) process.exit(1) } } process.on('SIGINT', () => shutdownHandler('SIGINT')) process.on('SIGTERM', () => shutdownHandler('SIGTERM')) process.on('beforeExit', async () => { await telemetry.shutdown() }) async function main() { const transport = new StdioServerTransport() await server.connect(transport) console.log('Server started successfully') } main().catch(async (error) => { console.error('Fatal error:', error) await telemetry.shutdown() process.exit(1) }) ``` -------------------------------- ### Implement Custom Data Processors in TypeScript Source: https://context7.com/shinzo-labs/shinzo-ts/llms.txt Defines custom functions to filter, transform, or redact telemetry data before export. It allows for conditional modification of telemetry based on specific criteria, such as removing sensitive arguments or adding custom metadata. This functionality relies on the `@shinzolabs/instrumentation-mcp` package and the `McpServer` from `@modelcontextprotocol/sdk/server/mcp.js`. ```typescript import { instrumentServer, TelemetryConfig } from "@shinzolabs/instrumentation-mcp" import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" const server = new McpServer({ name: "custom-processor-server", version: "1.0.0" }) const telemetryConfig: TelemetryConfig = { serverName: "custom-processor-server", serverVersion: "1.0.0", exporterEndpoint: "http://localhost:4318/v1", dataProcessors: [ // Remove sensitive tool arguments (telemetryData) => { if (telemetryData['mcp.tool.name'] === 'sensitive_operation') { for (const key of Object.keys(telemetryData)) { if (key.startsWith('mcp.request.argument')) { delete telemetryData[key] } } } return telemetryData }, // Add custom metadata (telemetryData) => { telemetryData['custom.environment'] = process.env.NODE_ENV || 'development' telemetryData['custom.region'] = process.env.AWS_REGION || 'unknown' return telemetryData }, // Filter by tool name (telemetryData) => { const excludedTools = ['internal_health_check', 'debug_ping'] if (excludedTools.includes(telemetryData['mcp.tool.name'])) { return null // Return null to skip this telemetry data } return telemetryData } ] } const telemetry = instrumentServer(server, telemetryConfig) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.