npm package: @sedata-ai/mcp
Description: Developer-First Observability for AI Agents
Latest version: 0.0.2

# @sedata-ai/mcp

Developer-First Observability for AI Agents - MCP Server Instrumentation Package

## Overview

This package provides comprehensive observability and safety features for Model Context Protocol (MCP) servers. It automatically instruments your MCP server with OpenTelemetry tracing and metrics, and includes built-in safety checking capabilities.

## Features

- 🔍 **Automatic Instrumentation**: Zero-config OpenTelemetry tracing and metrics for MCP servers
- 🛡️ **Safety Checking**: Built-in content safety validation for tool inputs
- 📊 **Metrics & Tracing**: Detailed performance and usage analytics
- 🔧 **Flexible Configuration**: Support for multiple telemetry backends
- 🚀 **Easy Integration**: Simple wrapper functions for existing MCP servers

## Installation

```bash
npm install @sedata-ai/mcp
```

## Quick Start

```typescript
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { instrumentServer, safetyCheck } from '@sedata-ai/mcp';
import type { TelemetryConfig } from '@sedata-ai/mcp';

const server = new McpServer({
  name: 'my-server',
  version: '1.0.0'
});

// Configure telemetry
const telemetryConfig: TelemetryConfig = {
  serverName: 'my-server',
  serverVersion: '1.0.0',
  exporterEndpoint: 'http://localhost:4318/v1',
  exporterAuth: {
    type: 'bearer',
    token: 'your-auth-token'
  }
};

// Initialize instrumentation
const telemetry = instrumentServer(server, telemetryConfig);

// Register tools with automatic safety checking
server.registerTool(
  'text-processor',
  {
    title: 'Text Processor',
    description: 'Process text content',
    inputSchema: {
      text: z.string()
    },
    outputSchema: { result: z.string() }
  },
  safetyCheck(async ({ text }) => {
    // Your tool logic here
    return {
      content: [{ type: 'text', text: `Processed: ${text}` }],
      structuredContent: { result: `Processed: ${text}` }
    };
  }, {
    parameterName: 'text',
    output_screen: true
  })
);
```

## Configuration

### Telemetry Configuration

The [`TelemetryConfig`](src/types.ts) interface supports the following options:

```typescript
interface TelemetryConfig {
  // Required
  serverName: string;
  serverVersion: string;
  
  // Optional
  exporterEndpoint?: string;           // OTLP endpoint URL
  exporterType?: 'otlp-http' | 'otlp-grpc' | 'console';
  
  // Authentication
  exporterAuth?: {
    type: 'bearer' | 'apiKey' | 'basic';
    token?: string;
    apiKey?: string;
    username?: string;
    password?: string;
  };
  
  // Sampling & Performance
  samplingRate?: number;               // 0.0 to 1.0 (default: 1.0)
  metricExportIntervalMs?: number;     // Default: 5000
  batchTimeoutMs?: number;             // Default: 2000
  
  // Features
  enablePIISanitization?: boolean;     // Default: true
  enableArgumentCollection?: boolean;   // Default: false
  enableMetrics?: boolean;             // Default: true
  enableTracing?: boolean;             // Default: true
  
  // Custom processing
  dataProcessors?: ((data: any) => any)[];
}
```

### Authentication Examples

#### Bearer Token
```typescript
const config: TelemetryConfig = {
  serverName: 'my-server',
  serverVersion: '1.0.0',
  exporterEndpoint: 'https://your-telemetry-endpoint.com/v1',
  exporterAuth: {
    type: 'bearer',
    token: 'your-bearer-token'
  }
};
```

#### API Key
```typescript
const config: TelemetryConfig = {
  serverName: 'my-server',
  serverVersion: '1.0.0',
  exporterEndpoint: 'https://your-telemetry-endpoint.com/v1',
  exporterAuth: {
    type: 'apiKey',
    apiKey: 'your-api-key'
  }
};
```

#### Console Output (Development)
```typescript
const config: TelemetryConfig = {
  serverName: 'my-server',
  serverVersion: '1.0.0',
  exporterType: 'console'  // No endpoint needed
};
```

## Safety Checking

The [`safetyCheck`](src/safety-check.ts) function wraps your tool handlers to validate input content:

```typescript
import { safetyCheck } from '@sedata-ai/mcp';

server.registerTool(
  'content-analyzer',
  toolConfig,
  safetyCheck(async (params) => {
    // Your tool implementation
  }, {
    parameterName: 'content',  // Parameter to check
    output_screen: true,       // Log safety alerts
    endpoint: 'http://localhost:5001/security/safety-check'  // Optional custom endpoint
  })
);
```

### Safety Check Features

- **Automatic Content Validation**: Checks specified parameters for malicious content
- **Configurable Blocking**: Returns safe error messages when content is flagged
- **Performance Tracking**: Measures safety check latency
- **Telemetry Integration**: Adds safety check results to spans and metrics

## Manual Telemetry Usage

You can also use telemetry features manually:

```typescript
const telemetry = instrumentServer(server, config);

// Create custom spans
telemetry.startActiveSpan('custom-operation', { 
  'custom.attribute': 'value' 
}, (span) => {
  // Your operation here
  span.setAttribute('result', 'success');
});

// Record metrics
const histogram = telemetry.getHistogram('custom.duration', {
  description: 'Custom operation duration',
  unit: 'ms'
});
histogram(100, { operation: 'example' });

const counter = telemetry.getIncrementCounter('custom.count', {
  description: 'Custom operation count'
});
counter(1, { status: 'success' });
```

## Metrics and Traces

### Automatic Metrics

- `mcp.server.operation.duration` - Tool execution duration
- `mcp.server.operation.count` - Tool execution count
- `mcp.server.session.duration` - Server session duration

### Automatic Trace Attributes

- `mcp.method.name` - MCP method being called
- `mcp.tool.name` - Tool name
- `mcp.tool.title` - Tool title
- `mcp.tool.description` - Tool description
- `mcp.request.id` - Unique request identifier
- `mcp.session.id` - Session identifier
- `mcp.safety_check.*` - Safety check results (when applicable)
- `client.address` - Client network address
- `client.port` - Client port (if available)

## Error Handling

The package gracefully handles various error scenarios:

- **Failed Safety Checks**: Continues execution with warnings
- **Telemetry Failures**: Never breaks your application
- **Network Issues**: Automatic retry and fallback mechanisms

## Examples

See the [`example-servers`](../example-servers/) directory for complete working examples:

- [TypeScript MCP Server](../example-servers/typescript-mcp-server/) - Shows full integration
- [Go MCP Server](../example-servers/golang-mcp-server/) - Reference implementation

## API Reference

### Functions

- [`instrumentServer(server, config)`](src/index.ts) - Main instrumentation function
- [`safetyCheck(handler, options)`](src/safety-check.ts) - Safety check wrapper
- [`checkSafety(content)`](src/safety-check.ts) - Direct safety check function

### Classes

- [`TelemetryManager`](src/telemetry.ts) - Core telemetry management
- [`McpServerInstrumentation`](src/instrumentation.ts) - MCP-specific instrumentation
- [`ConfigValidator`](src/config.ts) - Configuration validation

### Types

- [`TelemetryConfig`](src/types.ts) - Main configuration interface
- [`ObservabilityInstance`](src/types.ts) - Telemetry instance interface
- [`AuthConfig`](src/types.ts) - Authentication configuration

## Requirements

- Node.js >= 22.16
- `@modelcontextprotocol/sdk` >= 1.21.1

## License

See the main project license.

## Support

For questions and support, please refer to the main project documentation or create an issue in the repository.