# https://github.com/quietnotion/barevalue-mcp Project Manual

Generated on: 2026-05-24 16:52:56 UTC

## Table of Contents

- [Project Overview](#overview)
- [Installation Guide](#installation)
- [Configuration Reference](#configuration)
- [System Architecture](#system-architecture)
- [Data Flow](#data-flow)
- [Account and Billing Tools](#account-tools)
- [Order Workflow Tools](#order-workflow)
- [Webhook Management](#webhook-management)
- [Error Handling and Rate Limits](#error-handling)
- [Security](#security)

<a id='overview'></a>

## Project Overview

### Related Pages

Related topics: [Installation Guide](#installation), [System Architecture](#system-architecture)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)
- [package.json](https://github.com/quietnotion/barevalue-mcp/blob/main/package.json)
- [src/index.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)
- [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)
- [src/types.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/types.ts)
</details>

# Project Overview

## Introduction

**barevalue-mcp** is a Model Context Protocol (MCP) server that integrates the Barevalue AI podcast editing API into AI assistants like Claude Code. It enables programmatic submission of podcast episodes for AI-powered editing, along with order management, status tracking, and webhook configuration.

The project is implemented in TypeScript, built with the `@modelcontextprotocol/sdk`, and distributed as an npm package (`barevalue-mcp`). Source: [package.json](https://github.com/quietnotion/barevalue-mcp/blob/main/package.json)

## Purpose and Scope

This MCP server serves as a bridge between AI assistants and the Barevalue podcast editing service, providing:

- **Audio Upload**: Upload local audio files via presigned S3 URLs
- **Order Submission**: Submit podcast episodes for AI editing with customizable options
- **Status Tracking**: Monitor order progress through various processing stages
- **Account Management**: Query subscription minutes, credit balances, and pricing
- **Webhook Integration**: Configure webhooks for order completion notifications

Source: [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Architecture

The project follows a modular architecture with clear separation of concerns:

```mermaid
graph TD
    A[Claude Code / AI Assistant] -->|MCP Protocol| B[src/index.ts<br>MCP Server]
    B --> C[src/api-client.ts<br>API Client]
    C -->|HTTPS| D[Barevalue API<br>barevalue.com/api/v1]
    C -->|S3 Upload| E[AWS S3]
    
    F[src/types.ts<br>Type Definitions] --> B
    F --> C
    
    G[package.json] -->|npm dependencies| B
    G -->|@modelcontextprotocol/sdk| C
```

### Core Components

| Component | File | Responsibility |
|-----------|------|-----------------|
| MCP Server | `src/index.ts` | Handles MCP protocol communication, tool definitions, and request routing |
| API Client | `src/api-client.ts` | Encapsulates all Barevalue API calls including file uploads and webhooks |
| Type Definitions | `src/types.ts` | TypeScript interfaces for inputs, outputs, and API responses |

Source: [src/index.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts), [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts), [src/types.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/types.ts)

## Available Tools

The MCP server exposes the following tools organized by functional area:

### Account & Billing

| Tool | Description |
|------|-------------|
| `barevalue_account` | Get account information including credit balance, AI subscription status, and pricing |
| `barevalue_estimate` | Calculate the cost of an order before submission based on duration |

### Order Workflow

| Tool | Description |
|------|-------------|
| `barevalue_upload` | Upload a local audio file; returns `order_id` and `s3_key` for submission |
| `barevalue_validate` | Pre-check a file from a public URL before submission (external URLs only) |
| `barevalue_submit` | Submit an uploaded file for AI editing; charges credits |
| `barevalue_submit_url` | Submit using a public URL instead of uploading |
| `barevalue_status` | Check order status and retrieve download URLs when complete |
| `barevalue_list_orders` | List recent orders with pagination support |

### Webhook Management

| Tool | Description |
|------|-------------|
| `barevalue_list_webhooks` | List all configured webhooks |
| `barevalue_create_webhook` | Create a new webhook endpoint |
| `barevalue_get_webhook` | Get details of a specific webhook |
| `barevalue_update_webhook` | Update webhook URL, events, or active status |
| `barevalue_delete_webhook` | Delete a webhook |
| `barevalue_webhook_rotate_secret` | Rotate webhook secret for security |

Source: [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md), [src/index.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

## Complete Workflow

### Local File Upload Flow

```mermaid
sequenceDiagram
    participant User
    participant MCP as barevalue-mcp
    participant BV as Barevalue API
    participant S3 as AWS S3
    
    User->>MCP: barevalue_upload(file_path)
    MCP->>BV: getUploadUrl(filename, contentType)
    BV-->>MCP: presigned S3 URL + s3_key
    MCP->>S3: PUT file to presigned URL
    S3-->>MCP: upload confirmation
    MCP-->>User: order_id, s3_key
    
    User->>MCP: barevalue_submit(order_id, s3_key, ...)
    MCP->>BV: POST /orders/submit
    BV-->>MCP: order confirmation
    MCP-->>User: order submitted
    
    User->>MCP: barevalue_status(order_id)
    loop Until completed
        MCP->>BV: GET /orders/{id}
        BV-->>MCP: status update
        MCP-->>User: current status
    end
```

### External URL Flow

```mermaid
sequenceDiagram
    participant User
    participant MCP as barevalue-mcp
    participant BV as Barevalue API
    
    User->>MCP: barevalue_validate(file_url)
    MCP->>BV: validate file URL
    BV-->>MCP: validation result
    MCP-->>User: speech percentage, music detection
    
    User->>MCP: barevalue_submit_url(file_url, ...)
    MCP->>BV: POST /orders/submit-url
    BV-->>MCP: order confirmation
    MCP-->>User: order submitted
```

Source: [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Supported File Formats

The system supports the following audio formats for upload:

| Format | MIME Type | Extension |
|--------|-----------|-----------|
| MP3 | audio/mpeg | .mp3 |
| WAV | audio/wav | .wav |
| M4A | audio/mp4 | .m4a |
| FLAC | audio/flac | .flac |
| AAC | audio/aac | .aac |
| OGG | audio/ogg | .ogg |
| WMA | audio/x-ms-wma | .wma |
| AIFF | audio/aiff | .aiff, .aif |

**Maximum file size:** 750MB
**Minimum speech content:** 10% of audio must contain speech

Source: [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts), [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Configuration

### Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `BAREVALUE_API_KEY` | Yes | — | API key starting with `bv_sk_` |
| `BAREVALUE_API_URL` | No | `https://barevalue.com/api/v1` | Override API base URL |

### Claude Code Setup

```json
{
  "mcpServers": {
    "barevalue": {
      "command": "npx",
      "args": ["-y", "barevalue-mcp"],
      "env": {
        "BAREVALUE_API_KEY": "bv_sk_your_api_key_here"
      }
    }
  }
}
```

Or for global installation:

```json
{
  "mcpServers": {
    "barevalue": {
      "command": "barevalue-mcp",
      "env": {
        "BAREVALUE_API_KEY": "bv_sk_your_api_key_here"
      }
    }
  }
}
```

Source: [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Order Status Lifecycle

Orders progress through the following states:

```mermaid
stateDiagram-v2
    [*] --> pending: Submit order
    pending --> downloading: Start processing
    downloading --> transcribing: Download complete
    transcribing --> editing: Transcription done
    editing --> completed: Processing done
    editing --> failed: Error occurred
    completed --> [*]
    failed --> refunded: Refund issued
    refunded --> [*]
```

### Status Values

| Status | Description |
|--------|-------------|
| `pending` | Order received, waiting to start |
| `downloading` | Fetching audio file |
| `processing` | General processing |
| `transcribing` | Converting speech to text |
| `editing` | AI editing audio |
| `completed` | Ready for download |
| `failed` | Processing error |
| `refunded` | Credits refunded |

Source: [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md), [src/types.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/types.ts)

## Processing Options

When submitting an order, the following processing styles are available:

| Style | Description |
|-------|-------------|
| `standard` | Default editing level |
| `minimal` | Light editing, preserves more original content |
| `aggressive` | Heavy editing, removes more filler |

Additional options include:
- `host_names`: Array of host names for transcript speaker labels (max 5)
- `guest_names`: Array of guest names for transcript speaker labels (max 10)
- `special_instructions`: Custom editing instructions (max 2000 characters)

Source: [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md), [src/index.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

## Security

The implementation includes several security measures:

| Feature | Implementation |
|---------|----------------|
| API Key Validation | Keys must start with `bv_sk_` |
| HTTPS Enforcement | Warns when using non-HTTPS for non-localhost URLs |
| Error Message Sanitization | Raw API/S3 response data not exposed in errors |
| Environment Variable Storage | API key never hardcoded in source |

```typescript
// API key format validation
if (!this.apiKey.startsWith('bv_sk_')) {
  throw new Error(
    'Invalid API key format. Barevalue API keys must start with "bv_sk_".'
  );
}
```

Source: [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

## Rate Limits

| Limit | Value |
|-------|-------|
| Requests per minute | 10 per API key |
| File upload timeout | 5 minutes |
| Order processing time | 10-30 minutes typical |

Source: [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Error Handling

The API returns structured errors:

```json
{
  "error": "error_code",
  "message": "Human readable message",
  "statusCode": 400
}
```

### Common Error Codes

| Error Code | Meaning |
|------------|---------|
| `invalid_api_key` | API key missing, invalid, or revoked |
| `insufficient_credits` | Not enough credits or subscription minutes |
| `validation_failed` | File failed pre-checks |
| `file_too_large` | File exceeds 750MB limit |
| `rate_limited` | Too many requests (10/minute) |

Source: [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md), [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

## Development

### Prerequisites

- Node.js >= 18.0.0
- npm

### Build Commands

| Command | Action |
|---------|--------|
| `npm install` | Install dependencies |
| `npm run build` | Compile TypeScript to JavaScript |
| `npm run dev` | Watch mode compilation |
| `npm start` | Run production server |

### Project Structure

```
barevalue-mcp/
├── src/
│   ├── index.ts         # MCP server implementation
│   ├── api-client.ts    # Barevalue API client
│   └── types.ts         # TypeScript type definitions
├── package.json         # Project metadata and dependencies
├── server.json          # MCP server configuration for registries
├── README.md            # Documentation
└── dist/                # Compiled output (generated)
```

Source: [package.json](https://github.com/quietnotion/barevalue-mcp/blob/main/package.json), [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Deliverables

Every completed order includes:

| Deliverable | Description |
|-------------|-------------|
| Edited Audio | Audio with filler words, long pauses, and false starts removed |
| Transcript PDF | Formatted transcript document |
| Transcript DOCX | Editable Word document transcript |
| Show Notes | Timestamped show notes |
| Social Clips | AI-selected highlight clips |

Source: [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

---

<a id='installation'></a>

## Installation Guide

### Related Pages

Related topics: [Configuration Reference](#configuration), [Project Overview](#overview)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)
- [package.json](https://github.com/quietnotion/barevalue-mcp/blob/main/package.json)
- [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)
- [src/index.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)
- [src/types.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/types.ts)
- [server.json](https://github.com/quietnotion/barevalue-mcp/blob/main/server.json)
</details>

# Installation Guide

This guide covers all methods for installing and configuring the **barevalue-mcp** server, which provides a Model Context Protocol (MCP) interface for the Barevalue AI podcast editing API.

## Overview

The barevalue-mcp package is an MCP server that enables AI assistants like Claude Code to interact with the Barevalue podcast editing service. It exposes tools for uploading audio files, submitting editing orders, checking order status, and managing webhooks.

The server communicates with the Barevalue API over HTTPS, transmits the API key via environment variable, and uses stdio for MCP protocol communication with the host application.

**Source:** [README.md:1-5](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Prerequisites

Before installation, ensure your environment meets the following requirements:

| Requirement | Version | Notes |
|-------------|---------|-------|
| Node.js | >= 18.0.0 | Required runtime |
| npm | Latest stable | For package management |
| Claude Code | Compatible version | MCP host application |
| Barevalue Account | Active | With API key access |

**Source:** [package.json:19](https://github.com/quietnotion/barevalue-mcp/blob/main/package.json)

## Obtaining an API Key

An API key is required to authenticate with the Barevalue API. Follow these steps to obtain one:

1. Log in to your [Barevalue account](https://barevalue.com/login)
2. Navigate to **Settings** → **API Keys**
3. Click **Create API Key**
4. Copy the key (starts with `bv_sk_`) — it is only shown once

The API key format must start with `bv_sk_`. The API client validates this format on initialization and throws an error if the format is incorrect.

**Source:** [README.md:47-55](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

```typescript
// API key validation in api-client.ts
if (!this.apiKey.startsWith('bv_sk_')) {
  throw new Error(
    'Invalid API key format. Barevalue API keys must start with "bv_sk_".'
  );
}
```

**Source:** [src/api-client.ts:34-38](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

## Installation Methods

### Method 1: NPX (Recommended for Most Users)

The npx method downloads and executes the package without requiring a global installation. This is the simplest approach for most users.

Add the following configuration to your Claude Code settings file (`~/.claude/settings.json`):

```json
{
  "mcpServers": {
    "barevalue": {
      "command": "npx",
      "args": ["-y", "barevalue-mcp"],
      "env": {
        "BAREVALUE_API_KEY": "bv_sk_your_api_key_here"
      }
    }
  }
}
```

**Source:** [README.md:1-15](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

### Method 2: Global Install

For environments where npx execution is not preferred, install the package globally:

```bash
npm install -g barevalue-mcp
```

Then configure Claude Code with the global command:

```json
{
  "mcpServers": {
    "barevalue": {
      "command": "barevalue-mcp",
      "env": {
        "BAREVALUE_API_KEY": "bv_sk_your_api_key_here"
      }
    }
  }
}
```

**Source:** [README.md:20-35](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Configuration

### Claude Code Settings File

The MCP server configuration is stored in your Claude Code settings file. The default location is:

```
~/.claude/settings.json
```

### Configuration Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `command` | string | Yes | Executable command (`npx` or `barevalue-mcp`) |
| `args` | array | No (npx only) | Arguments for the command (`["-y", "barevalue-mcp"]`) |
| `env` | object | Yes | Environment variables |
| `env.BAREVALUE_API_KEY` | string | Yes | Your Barevalue API key |

**Source:** [README.md:8-14](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

### Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `BAREVALUE_API_KEY` | Yes | — | API key starting with `bv_sk_` |
| `BAREVALUE_API_URL` | No | `https://barevalue.com/api/v1` | Override API base URL |

**Source:** [README.md:59-62](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

The API client reads these environment variables on initialization:

```typescript
this.apiKey = process.env.BAREVALUE_API_KEY || '';
this.baseUrl = process.env.BAREVALUE_API_URL || 'https://barevalue.com/api/v1';
```

**Source:** [src/api-client.ts:28-32](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

## Security Configuration

### HTTPS Enforcement

The API client enforces HTTPS for non-localhost connections. If the configured base URL uses HTTP, a warning is logged:

```typescript
const url = new URL(this.baseUrl);
const isHttps = url.protocol === 'https:';
if (!isHttps && url.hostname !== 'localhost' && url.hostname !== '127.0.0.1') {
  console.error('WARNING: Using non-HTTPS connection. API key may be transmitted insecurely.');
}
```

**Source:** [src/api-client.ts:39-45](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

### API Key Transmission

API keys are transmitted exclusively via the `Authorization` header using Bearer token authentication:

```typescript
headers: {
  'Authorization': `Bearer ${this.apiKey}`,
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'User-Agent': 'barevalue-mcp/1.0.0',
}
```

**Source:** [src/api-client.ts:59-65](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

## Development Installation

For contributors or those who want to run from source, follow these steps:

```bash
# Install dependencies
npm install

# Build the TypeScript project
npm run build

# Run in watch mode during development
npm run dev

# Start the production server
npm start
```

**Source:** [README.md:142-151](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

### Build Scripts

The following npm scripts are defined in package.json:

| Script | Command | Purpose |
|--------|---------|---------|
| `build` | `tsc` | Compile TypeScript to JavaScript |
| `dev` | `tsc --watch` | Watch mode for development |
| `start` | `node dist/index.js` | Run production server |
| `prepublishOnly` | `npm run build` | Build before publishing |

**Source:** [package.json:9-14](https://github.com/quietnotion/barevalue-mcp/blob/main/package.json)

### Dependencies

The project has the following runtime dependencies:

| Package | Version | Purpose |
|---------|---------|---------|
| `@modelcontextprotocol/sdk` | ^1.0.0 | MCP protocol implementation |

**Source:** [package.json:22-26](https://github.com/quietnotion/barevalue-mcp/blob/main/package.json)

## Server Initialization

The MCP server starts by initializing the SDK with the server name and version:

```typescript
const server = new Server(
  {
    name: 'barevalue-mcp',
    version: '1.0.0',
  },
  {
    capabilities: {
      tools: {},
    },
  }
);
```

**Source:** [src/index.ts:120-130](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

The server registers two request handlers:

1. **ListToolsRequestSchema** — Returns all available MCP tools
2. **CallToolRequestSchema** — Executes tool calls by name

```typescript
server.setRequestHandler(ListToolsRequestSchema, async () => {
  return { tools: TOOLS };
});

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const { name, arguments: args } = request.params;
  return handleToolCall(name, args as Record<string, unknown>);
});
```

**Source:** [src/index.ts:132-142](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

## MCP Server Metadata

The server.json file defines MCP registry metadata:

```json
{
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
  "name": "io.github.quietnotion/barevalue",
  "title": "Barevalue",
  "description": "Submit podcast orders, check status, and manage webhooks via Barevalue editing API.",
  "version": "1.0.3"
}
```

**Source:** [server.json:1-7](https://github.com/quietnotion/barevalue-mcp/blob/main/server.json)

### NPM Package Metadata

| Field | Value |
|-------|-------|
| Package Name | `barevalue-mcp` |
| Version | `1.0.3` |
| MCP Name | `io.github.quietnotion/barevalue` |
| Main Entry | `dist/index.js` |
| License | MIT |

**Source:** [package.json:1-6](https://github.com/quietnotion/barevalue-mcp/blob/main/package.json)

## Installation Flow

The following diagram illustrates the complete installation and configuration flow:

```mermaid
graph TD
    A[Start Installation] --> B{Have Node.js >= 18?}
    B -->|No| C[Install Node.js]
    C --> D
    B -->|Yes| D{Have Barevalue API Key?}
    D -->|No| E[Create API Key at barevalue.com]
    E --> F
    D -->|Yes| F{Choose Installation Method}
    F -->|npx| G[Add MCP Config to settings.json]
    F -->|global| H[Run npm install -g barevalue-mcp]
    H --> I[Add MCP Config to settings.json]
    G --> J[Restart Claude Code]
    I --> J
    J --> K[Server Ready]
    K --> L[Check with barevalue_account tool]
```

## Available Tools After Installation

Once installed and configured, the following MCP tools become available:

| Tool | Purpose |
|------|---------|
| `barevalue_account` | Get account information and credit balance |
| `barevalue_estimate` | Calculate order cost before submission |
| `barevalue_upload` | Upload local audio file |
| `barevalue_validate` | Validate external URL before submission |
| `barevalue_submit` | Submit uploaded file for editing |
| `barevalue_submit_url` | Submit external URL for editing |
| `barevalue_status` | Check order status |
| `barevalue_list_orders` | List recent orders |
| `barevalue_webhook_*` | Webhook management tools |

**Source:** [src/index.ts:54-112](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

## Verifying Installation

After installation, verify the setup by checking your account balance:

```
User: Check my Barevalue account balance

Claude: [calls barevalue_account]

Your account information:
- Balance: X credits
- Subscription: [plan name]
- AI Minutes: [available minutes]
```

## Troubleshooting

### Common Issues

| Issue | Solution |
|-------|----------|
| `invalid_api_key` error | Ensure API key starts with `bv_sk_` |
| Connection timeout | Check network/firewall settings |
| Server won't start | Verify Node.js >= 18.0.0 |
| Tools not appearing | Restart Claude Code after config changes |

**Source:** [README.md:114-121](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Support

- **Documentation:** https://barevalue.com/docs/api-v1
- **Email:** support@barevalue.com

**Source:** [README.md:155-156](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

---

<a id='configuration'></a>

## Configuration Reference

### Related Pages

Related topics: [Installation Guide](#installation), [Security](#security)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)
- [server.json](https://github.com/quietnotion/barevalue-mcp/blob/main/server.json)
- [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)
- [src/index.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)
- [src/types.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/types.ts)
- [package.json](https://github.com/quietnotion/barevalue-mcp/blob/main/package.json)
</details>

# Configuration Reference

This page documents all configuration options available for the barevalue-mcp server, including environment variables, Claude Code integration, and runtime settings.

## Overview

The barevalue-mcp server is a Model Context Protocol (MCP) server that integrates with the Barevalue AI podcast editing API. Configuration is primarily driven through environment variables and JSON configuration files for Claude Code integration.

**Source:** [server.json:1-20](https://github.com/quietnotion/barevalue-mcp/blob/main/server.json)

## Environment Variables

The server supports the following environment variables for configuration:

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `BAREVALUE_API_KEY` | Yes | - | Your Barevalue API key (must start with `bv_sk_`) |
| `BAREVALUE_API_URL` | No | `https://barevalue.com/api/v1` | Override API base URL |

**Source:** [README.md:1-50](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

### Obtaining an API Key

1. Log in to your [Barevalue account](https://barevalue.com/login)
2. Navigate to **Settings** → **API Keys**
3. Click **Create API Key**
4. Copy the key (starts with `bv_sk_`)

**Important:** The API key is only shown once during creation. Store it securely.

**Source:** [README.md:45-60](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Claude Code Integration

### Configuration File Location

Add the barevalue-mcp server to your Claude Code settings file at `~/.claude/settings.json`.

**Source:** [README.md:35-45](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

### Option 1: NPX (Recommended)

```json
{
  "mcpServers": {
    "barevalue": {
      "command": "npx",
      "args": ["-y", "barevalue-mcp"],
      "env": {
        "BAREVALUE_API_KEY": "bv_sk_your_api_key_here"
      }
    }
  }
}
```

**Source:** [README.md:1-15](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

### Option 2: Global Install

```bash
npm install -g barevalue-mcp
```

Then configure with the installed command:

```json
{
  "mcpServers": {
    "barevalue": {
      "command": "barevalue-mcp",
      "env": {
        "BAREVALUE_API_KEY": "bv_sk_your_api_key_here"
      }
    }
  }
}
```

**Source:** [README.md:20-35](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Server Metadata

The MCP server announces the following metadata to Claude Code:

| Property | Value |
|----------|-------|
| Server Name | `io.github.quietnotion/barevalue` |
| Display Name | `Barevalue` |
| Version | `1.0.3` |
| Transport | `stdio` |
| Package | `barevalue-mcp` |

**Source:** [server.json:1-25](https://github.com/quietnotion/barevalue-mcp/blob/main/server.json)

## Available Tools Configuration

The server exposes the following tools, each with specific input requirements:

**Source:** [src/index.ts:50-150](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

### Tool Input Schemas

#### barevalue_account

```json
{
  "type": "object",
  "properties": {},
  "required": []
}
```

**Source:** [src/index.ts:55-65](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

#### barevalue_estimate

```json
{
  "type": "object",
  "properties": {
    "duration_minutes": {
      "type": "number",
      "description": "Audio duration in minutes (1-300)"
    }
  },
  "required": ["duration_minutes"]
}
```

**Source:** [src/index.ts:70-85](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

#### barevalue_upload

```json
{
  "type": "object",
  "properties": {
    "file_path": {
      "type": "string",
      "description": "Path to the audio file on your local machine"
    }
  },
  "required": ["file_path"]
}
```

**Source:** [src/index.ts:90-105](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

#### barevalue_submit

```json
{
  "type": "object",
  "properties": {
    "order_id": { "type": "number" },
    "s3_key": { "type": "string" },
    "podcast_name": { "type": "string" },
    "episode_name": { "type": "string" },
    "episode_number": { "type": "string" },
    "special_instructions": { "type": "string", "maxLength": 2000 },
    "processing_style": {
      "type": "string",
      "enum": ["standard", "minimal", "aggressive"]
    },
    "host_names": { "type": "array", "items": { "type": "string" }, "maxItems": 5 },
    "guest_names": { "type": "array", "items": { "type": "string" }, "maxItems": 10 }
  },
  "required": ["order_id", "s3_key", "podcast_name", "episode_name"]
}
```

**Source:** [src/types.ts:1-30](https://github.com/quietnotion/barevalue-mcp/blob/main/src/types.ts)

## Security Configuration

### API Key Validation

The server validates API key format on initialization:

```typescript
if (!this.apiKey.startsWith('bv_sk_')) {
  throw new Error(
    'Invalid API key format. Barevalue API keys must start with "bv_sk_".'
  );
}
```

**Source:** [src/api-client.ts:20-30](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

### HTTPS Enforcement

Non-HTTPS connections are blocked for non-localhost URLs with a warning:

```typescript
const isHttps = url.protocol === 'https:';
if (!isHttps && url.hostname !== 'localhost' && url.hostname !== '127.0.0.1') {
  console.error('WARNING: Using non-HTTPS connection. API key may be transmitted insecurely.');
}
```

**Source:** [src/api-client.ts:25-35](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

### Sensitive Directory Protection

File uploads are blocked from sensitive system directories:

```typescript
const sensitivePatterns = [
  /^\/etc\//,
  /^\/var\//,
  /^\/usr\//,
  /^\/root\//,
  /[/\\]\.ssh[/\\]/,
  /[/\\]\.aws[/\\]/,
  /[/\\]\.gnupg[/\\]/,
  /[/\\]\.config[/\\]/,
  /[/\\]\.env$/,
  /[/\\]\.env\./,
];
```

**Source:** [src/api-client.ts:150-165](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

## File Upload Configuration

### Supported Formats

| Extension | MIME Type |
|-----------|-----------|
| `.mp3` | audio/mpeg |
| `.wav` | audio/wav |
| `.m4a` | audio/mp4 |
| `.flac` | audio/flac |
| `.aac` | audio/aac |
| `.ogg` | audio/ogg |
| `.wma` | audio/x-ms-wma |
| `.aiff` / `.aif` | audio/aiff |

**Source:** [src/api-client.ts:65-85](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

### File Size Limits

| Limit | Value |
|-------|-------|
| Maximum file size | 750 MB |
| Upload timeout | 5 minutes |

**Source:** [README.md:100-110](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

### Presigned URL Expiration

S3 presigned URLs expire after **30 minutes** for security.

**Source:** [README.md:130-135](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Rate Limiting

| Limit | Value |
|-------|-------|
| Requests per minute | 10 per API key |
| File upload timeout | 5 minutes |
| Order processing | 10-30 minutes typical |

**Source:** [README.md:100-115](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Error Handling Configuration

### Error Response Structure

All API errors follow a standardized format:

```json
{
  "error": "error_code",
  "message": "Human readable description",
  "statusCode": 400
}
```

**Source:** [README.md:140-155](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

### Error Codes

| Code | Description |
|------|-------------|
| `invalid_api_key` | API key is missing, invalid, or revoked |
| `insufficient_credits` | Not enough credits or subscription minutes |
| `validation_failed` | File failed pre-checks (not enough speech, music detected) |
| `file_too_large` | File exceeds 750MB limit |
| `rate_limited` | Too many requests (limit: 10/minute) |

**Source:** [README.md:155-170](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Development Configuration

### Local Development Setup

```bash
# Install dependencies
npm install

# Build TypeScript
npm run build

# Watch mode (auto-rebuild on changes)
npm run dev

# Start production server
npm start
```

**Source:** [README.md:175-190](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

### Package Configuration

| Property | Value |
|----------|-------|
| Package Name | barevalue-mcp |
| Version | 1.0.3 |
| Entry Point | dist/index.js |
| CLI Bin | barevalue-mcp |
| Node Requirement | >=18.0.0 |

**Source:** [package.json:1-20](https://github.com/quietnotion/barevalue-mcp/blob/main/package.json)

## Configuration Flow

```mermaid
graph TD
    A[Start] --> B{API Key Set?}
    B -->|No| C[Error: API key required]
    B -->|Yes| D{Valid Format bv_sk_*?}
    D -->|No| E[Error: Invalid format]
    D -->|Yes| F{HTTPS URL?}
    F -->|No| G[Check: localhost?]
    G -->|No| H[Warning: Insecure transmission]
    G -->|Yes| I[Allow HTTP]
    H --> J[Initialize API Client]
    I --> J
    F -->|Yes| J
    J --> K[Connect via StdioTransport]
    K --> L[Server Ready]
```

## Quick Reference

### Minimal Configuration (NPX)

```json
{
  "mcpServers": {
    "barevalue": {
      "command": "npx",
      "args": ["-y", "barevalue-mcp"],
      "env": {
        "BAREVALUE_API_KEY": "bv_sk_your_api_key_here"
      }
    }
  }
}
```

### Environment Variables Summary

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `BAREVALUE_API_KEY` | Yes | - | API key starting with `bv_sk_` |
| `BAREVALUE_API_URL` | No | `https://barevalue.com/api/v1` | Custom API endpoint |

### Node.js Requirements

- **Minimum version:** Node.js 18.0.0
- **Recommended:** Latest LTS version

---

<a id='system-architecture'></a>

## System Architecture

### Related Pages

Related topics: [Data Flow](#data-flow), [Project Overview](#overview)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/index.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)
- [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)
- [src/types.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/types.ts)
</details>

# System Architecture

## Overview

The barevalue-mcp is a Model Context Protocol (MCP) server that enables AI assistants like Claude to interact with the Barevalue podcast editing API. It provides a bridge between MCP-compatible clients and the Barevalue backend services, allowing users to submit podcast files for AI editing, monitor order status, and manage webhooks through natural language commands.

The architecture follows a client-server pattern where the MCP server acts as an intermediary, translating MCP tool calls into HTTP API requests and formatting responses for consumption by the AI assistant.

## High-Level Architecture

```mermaid
graph TD
    subgraph "MCP Client (Claude Code)"
        A[User Request]
    end
    
    subgraph "Barevalue MCP Server"
        B[MCP Server]
        C[Tool Router]
        D[Data Sanitizer]
        E[API Client]
    end
    
    subgraph "External Services"
        F[Barevalue API]
        G[AWS S3]
    end
    
    A --> B
    B --> C
    C --> D
    C --> E
    E --> F
    E --> G
```

## Component Architecture

### Core Components

| Component | File | Responsibility |
|-----------|------|----------------|
| MCP Server | `src/index.ts` | Entry point, request routing, tool definitions |
| API Client | `src/api-client.ts` | HTTP communication with Barevalue API |
| Type Definitions | `src/types.ts` | TypeScript interfaces for all data models |
| Tool Registry | `src/index.ts` | Tool definitions and input schema validation |
| Error Handler | `src/api-client.ts` | Custom error class and error handling |

### MCP Server (`src/index.ts`)

The MCP server is built using the `@modelcontextprotocol/sdk` package and implements the server-side of the MCP protocol. It handles two primary request types: `ListToolsRequestSchema` and `CallToolRequestSchema`.

**Server Initialization** (lines 1-100):
```typescript
const server = new Server(
  {
    name: 'barevalue-mcp',
    version: '1.0.0',
  },
  {
    capabilities: {
      tools: {},
    },
  }
);
```

**Request Handling Flow:**

```mermaid
graph TD
    A[Incoming Request] --> B{Route to Handler}
    B -->|ListTools| C[Return Tool Definitions]
    B -->|CallTool| D[Extract Tool Name]
    D --> E[Extract Arguments]
    E --> F[Validate Input Schema]
    F -->|Invalid| G[Return Error]
    F -->|Valid| H[Execute Tool Handler]
    H --> I[Sanitize Output]
    I --> J[Return MCP Response]
```

The server defines 12 tools organized into three functional categories:

1. **Account & Billing Tools**
   - `barevalue_account` - Get account information
   - `barevalue_estimate` - Calculate order cost

2. **Order Workflow Tools**
   - `barevalue_upload` - Upload local files
   - `barevalue_validate` - Validate external URLs
   - `barevalue_submit` - Submit for editing
   - `barevalue_submit_url` - Submit via URL
   - `barevalue_status` - Check order status
   - `barevalue_list_orders` - List recent orders

3. **Webhook Management Tools**
   - `barevalue_list_webhooks` - List webhooks
   - `barevalue_create_webhook` - Create webhook
   - `barevalue_delete_webhook` - Delete webhook
   - `barevalue_webhook_rotate_secret` - Rotate webhook secret

### API Client (`src/api-client.ts`)

The `BarevalueApiClient` class encapsulates all HTTP communication with the Barevalue API. It uses native Node.js `http` and `https` modules for making requests.

**Class Structure:**

```typescript
export class BarevalueApiClient {
  private readonly apiKey: string;
  private readonly baseUrl: string;
  private readonly timeout: number;

  constructor(apiKey: string, baseUrl?: string, timeout?: number) {
    // Initialization
  }
  
  // Request methods
  private async request<T>(method: string, endpoint: string, body?: Record<string, unknown>): Promise<T>
  
  // Order methods
  async getAccount(): Promise<AccountInfo>
  async estimateCost(durationMinutes: number): Promise<EstimateResponse>
  async getUploadUrl(): Promise<UploadUrlResponse>
  async uploadFile(uploadUrl: string, filePath: string): Promise<void>
  async validateUrl(fileUrl: string): Promise<ValidateResponse>
  async submitOrder(params: SubmitParams): Promise<OrderStatus>
  async submitExternalUrl(params: SubmitUrlParams): Promise<OrderStatus>
  async getOrderStatus(orderId: number): Promise<OrderStatus>
  async listOrders(params?: ListOrdersParams): Promise<OrderListResponse>
  
  // Webhook methods
  async listWebhooks(): Promise<WebhookListResponse>
  async createWebhook(url: string, events: string[]): Promise<Webhook>
  async getWebhook(webhookId: number): Promise<Webhook>
  async updateWebhook(webhookId: number, updates: WebhookUpdates): Promise<Webhook>
  async deleteWebhook(webhookId: number): Promise<{ success: boolean }>
  async rotateWebhookSecret(webhookId: number): Promise<Webhook>
}
```

**HTTP Request Flow:**

```mermaid
sequenceDiagram
    participant Tool as Tool Handler
    participant Client as API Client
    participant API as Barevalue API
    participant S3 as AWS S3

    Tool->>Client: call method(params)
    Client->>Client: validateApiKey()
    Client->>Client: buildRequest()
    Client->>API: HTTP Request
    API-->>Client: JSON Response
    Client->>Client: checkStatusCode()
    Client-->>Tool: parsed response
    Note over Tool,Client: For uploads
    Tool->>Client: uploadFile()
    Client->>S3: Presigned URL PUT
    S3-->>Client: Upload Complete
```

**Security Features** (lines 30-40):

The API client implements several security measures:

1. **API Key Validation** - Verifies keys start with `bv_sk_`
2. **HTTPS Enforcement** - Warns if using non-HTTPS for non-localhost URLs
3. **Timeout Protection** - Configurable request timeout (default: 5 minutes)
4. **Error Sanitization** - Raw API responses are not exposed in error messages

```typescript
// Security: Don't expose S3 error response data
reject(new Error(`S3 upload failed with status ${res.statusCode}`));

// Security: Don't expose raw API response data in error messages
reject(new Error('Failed to parse API response'));
```

### Error Handling Architecture

The `BarevalueApiError` class provides structured error handling:

```typescript
export class BarevalueApiError extends Error {
  constructor(
    message: string,
    public readonly code: string,
    public readonly statusCode: number,
    public readonly details?: Record<string, unknown>
  ) {
    super(message);
    this.name = 'BarevalueApiError';
  }
}
```

**Error Response Format:**

| Error Code | Status | Meaning |
|------------|--------|---------|
| `invalid_api_key` | 401 | API key is missing, invalid, or revoked |
| `insufficient_credits` | 402 | Not enough credits or subscription minutes |
| `validation_failed` | 400 | File failed pre-checks |
| `file_too_large` | 413 | File exceeds 750MB limit |
| `rate_limited` | 429 | Too many requests (10/minute limit) |

## Data Flow Architecture

### Order Submission Flow

```mermaid
graph LR
    A[User Request] --> B[Upload Local File]
    B --> C[Get Presigned URL]
    C --> D[Upload to S3]
    D --> E[Submit Order]
    E --> F[Get Order ID]
    F --> G[Poll Status]
    G --> H[Return Results]
```

### Complete Order Workflow

```mermaid
stateDiagram-v2
    [*] --> Uploaded: barevalue_upload
    Uploaded --> Validating: barevalue_validate (optional)
    Uploaded --> Submitting: barevalue_submit
    Validating --> Submitting: validation passed
    Validating --> [*]: validation failed
    Submitting --> Processing: order created
    Processing --> Downloading: file download
    Downloading --> Transcribing: download complete
    Transcribing --> Editing: transcription complete
    Editing --> Completed: editing finished
    Completed --> [*]
    Processing --> Failed: error occurred
    Failed --> Refunded: refund processed
    Refunded --> [*]
```

## Type System Architecture

### Response Types (`src/types.ts`)

The type system is organized into response types and input types:

**Account Information:**
```typescript
interface AccountInfo {
  user: {
    id: number;
    email: string;
    name: string | null;
    is_verified: boolean;
    locale: string;
  };
  credits: {
    balance: number;
    currency: string;
  };
  ai_subscription: {
    tier: string | null;
    status: string | null;
    minutes_limit: number | null;
    minutes_used: number | null;
    minutes_remaining: number | null;
    period_end: string | null;
    pending_tier: string | null;
  } | null;
  ai_bonus_minutes: {
    balance: number;
    expires_at: string | null;
  };
  pricing: {
    audio_per_minute: number;
    currency: string;
  };
}
```

**Order Status:**
```typescript
interface OrderStatus {
  order_id: number;
  status: 'pending' | 'downloading' | 'processing' | 'transcribing' | 'editing' | 'completed' | 'failed' | 'refunded';
  created_at: string;
  updated_at: string;
  // Present when completed
  edited_audio_url?: string;
  transcript_pdf_url?: string;
  transcript_docx_url?: string;
  show_notes_url?: string;
}
```

### Tool Input Schemas

Each tool has a corresponding input schema defined in the tool definition:

| Tool | Required Parameters | Optional Parameters |
|------|---------------------|---------------------|
| `barevalue_estimate` | `duration_minutes` | - |
| `barevalue_upload` | `file_path` | `filename` |
| `barevalue_validate` | `file_url` | - |
| `barevalue_submit` | `order_id`, `s3_key`, `podcast_name`, `episode_name` | `episode_number`, `special_instructions`, `processing_style`, `host_names`, `guest_names` |
| `barevalue_submit_url` | `file_url`, `podcast_name`, `episode_name` | `episode_number`, `special_instructions`, `processing_style`, `host_names`, `guest_names` |
| `barevalue_status` | `order_id` | - |
| `barevalue_list_orders` | - | `page`, `per_page`, `status` |
| `barevalue_create_webhook` | `url`, `events` | - |
| `barevalue_delete_webhook` | `webhook_id` | - |

## Configuration

### Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `BAREVALUE_API_KEY` | Yes | - | API key (starts with `bv_sk_`) |
| `BAREVALUE_API_URL` | No | `https://barevalue.com/api/v1` | Override API base URL |

### MCP Server Configuration

```json
{
  "mcpServers": {
    "barevalue": {
      "command": "npx",
      "args": ["-y", "barevalue-mcp"],
      "env": {
        "BAREVALUE_API_KEY": "bv_sk_your_api_key_here"
      }
    }
  }
}
```

## Data Sanitization

The server implements input sanitization to prevent injection attacks. The `sanitizeString` function handles string escaping:

```typescript
function sanitizeString(input: unknown): string {
  if (typeof input !== 'string') return '';
  return input
    .replace(/[<>]/g, '')
    .slice(0, 10000);
}
```

This sanitization is applied to:
- Error messages
- Tool output data
- Key-value pairs in objects

## Transport Layer

The MCP server uses STDIO transport for communication with the client:

```typescript
const transport = new StdioServerTransport();
await server.connect(transport);
```

This architecture allows:
- Standard input/output based communication
- No network configuration required
- Easy integration with CLI tools and AI assistants

## Build and Development

| Command | Purpose |
|---------|---------|
| `npm install` | Install dependencies |
| `npm run build` | Compile TypeScript to JavaScript |
| `npm run dev` | Watch mode compilation |
| `npm start` | Run compiled server |
| `npm run prepublishOnly` | Build before npm publish |

Source: [package.json](https://github.com/quietnotion/barevalue-mcp/blob/main/package.json)

## Summary

The barevalue-mcp system architecture consists of three primary layers:

1. **Presentation Layer** - MCP tool definitions and request handling in `src/index.ts`
2. **Business Logic Layer** - API client with security features and error handling in `src/api-client.ts`
3. **Type Layer** - TypeScript interfaces for type safety in `src/types.ts`

The architecture prioritizes security through API key validation, HTTPS enforcement, and response sanitization, while maintaining a clean separation of concerns that facilitates testing and maintenance.

---

<a id='data-flow'></a>

## Data Flow

### Related Pages

Related topics: [System Architecture](#system-architecture), [Order Workflow Tools](#order-workflow)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/index.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)
- [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)
- [src/types.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/types.ts)
- [server.json](https://github.com/quietnotion/barevalue-mcp/blob/main/server.json)
</details>

# Data Flow

This document describes the data flow architecture of the barevalue-mcp server, covering how data moves from the client through the MCP protocol layer, through the API client, and ultimately to the Barevalue API.

## Overview

The barevalue-mcp server implements a Model Context Protocol (MCP) server that acts as a bridge between AI assistants (like Claude Code) and the Barevalue podcast editing API. Data flows through several distinct layers, each with specific responsibilities for validation, transformation, and security. Source: [src/index.ts:1-200](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

## Architecture Layers

The data flow consists of four primary layers:

| Layer | Component | Responsibility |
|-------|-----------|----------------|
| Transport | StdioServerTransport | JSON-RPC communication with MCP client |
| Protocol | Server (MCP SDK) | Request routing and capability negotiation |
| Application | Tool Handlers | Business logic and data transformation |
| External | ApiClient | HTTP communication with Barevalue API |

Source: [src/index.ts:280-320](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

## Request Flow

```mermaid
graph TD
    A["MCP Client<br/>(Claude Code)"] --> B["StdioServerTransport"]
    B --> C["Server<br/>MCP Protocol Handler"]
    C --> D["handleToolCall<br/>Router"]
    D --> E1["Account Handler"]
    D --> E2["Estimate Handler"]
    D --> E3["Upload Handler"]
    D --> E4["Submit Handler"]
    D --> E5["Status Handler"]
    D --> E6["Webhook Handler"]
    E1 --> F["ApiClient"]
    E2 --> F
    E3 --> F
    E4 --> F
    E5 --> F
    E6 --> F
    F --> G["Barevalue API"]
    G --> F
    F --> H["sanitizeData"]
    H --> I["MCP Response"]
    I --> B
    B --> A
```

### Step-by-Step Data Flow

1. **Client Request**: The MCP client sends a JSON-RPC request via stdio containing the tool name and arguments.
2. **Transport Reception**: The StdioServerTransport receives the raw JSON-RPC message.
3. **Protocol Parsing**: The MCP Server parses the request and extracts tool name and parameters.
4. **Routing**: The `handleToolCall` function routes to the appropriate handler based on the tool name.
5. **Handler Processing**: Each handler invokes the corresponding ApiClient method.
6. **API Communication**: The ApiClient makes HTTP requests to the Barevalue API.
7. **Data Sanitization**: All responses pass through `sanitizeData` before being returned.
8. **Response Serialization**: The server serializes the response as JSON-RPC and sends it back.

Source: [src/index.ts:220-280](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

## Input Data Sanitization

All incoming data undergoes sanitization before processing. The `sanitizeData` function recursively processes data structures to prevent injection attacks and ensure consistent formatting.

```typescript
function sanitizeData(data: unknown): unknown {
  if (typeof data === 'string') {
    return sanitizeString(data);
  }
  if (Array.isArray(data)) {
    return data.map(sanitizeData);
  }
  if (data !== null && typeof data === 'object') {
    const result: Record<string, unknown> = {};
    for (const [key, value] of Object.entries(data)) {
      result[sanitizeString(key)] = sanitizeData(value);
    }
    return result;
  }
  return data;
}
```

Source: [src/index.ts:10-26](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

The sanitization process:
- Recursively processes all strings using `sanitizeString`
- Maps over arrays applying sanitization to each element
- Creates new objects with sanitized keys and values
- Returns primitives unchanged

## API Client Data Flow

The ApiClient class manages all external API communication. It handles authentication, request construction, response parsing, and error handling.

```mermaid
graph LR
    A["Tool Handler"] --> B["ApiClient.request<T>"]
    B --> C["URL Construction"]
    C --> D["HTTPS Request"]
    D --> E["Response Parser"]
    E -->|Success| F["Typed Response"]
    E -->|Error| G["BarevalueApiError"]
    F --> H["Tool Handler"]
    G --> H
```

### Request Construction

The `request` method constructs HTTP requests with the following components:

| Component | Value | Purpose |
|-----------|-------|---------|
| Authorization | `Bearer ${apiKey}` | API authentication |
| Content-Type | `application/json` | Request body format |
| Accept | `application/json` | Response format |
| User-Agent | `barevalue-mcp/1.0.0` | Client identification |
| Timeout | 30000ms | Request timeout |

Source: [src/api-client.ts:120-150](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

### URL Resolution

The base URL defaults to `https://barevalue.com/api/v1` but can be overridden via the `BAREVALUE_API_URL` environment variable. The request method constructs the full URL by appending the endpoint:

```typescript
const cleanEndpoint = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint;
const cleanBase = this.baseUrl.endsWith('/') ? this.baseUrl : this.baseUrl + '/';
const fullUrl = cleanBase + cleanEndpoint;
```

Source: [src/api-client.ts:95-105](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

## File Upload Flow

File uploads follow a two-phase process: first obtaining a presigned URL, then uploading directly to S3.

```mermaid
sequenceDiagram
    participant C as Tool Handler
    participant AC as ApiClient
    participant BV as Barevalue API
    participant S3 as AWS S3

    C->>AC: uploadFile(filePath)
    AC->>BV
Error with Openai API: output new_sensitive (1027)

Please check that you have set the OPENAI_API_KEY environment variable with a valid API key.

---

<a id='account-tools'></a>

## Account and Billing Tools

### Related Pages

Related topics: [Order Workflow Tools](#order-workflow), [Error Handling and Rate Limits](#error-handling)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/index.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)
- [src/types.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/types.ts)
- [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)
- [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)
- [server.json](https://github.com/quietnotion/barevalue-mcp/blob/main/server.json)
</details>

# Account and Billing Tools

The Account and Billing Tools constitute the foundational layer of the Barevalue MCP server, providing essential functionality for monitoring account resources, checking credit balances, and estimating order costs before submission. These tools enable AI assistants to make informed decisions about podcast editing orders by providing real-time visibility into account status and available resources.

## Overview

The Account and Billing module consists of two primary MCP tools that interact with the Barevalue API's account endpoints:

| Tool Name | Purpose | API Endpoint |
|-----------|---------|--------------|
| `barevalue_account` | Retrieve comprehensive account information including balance and subscription status | `GET /account` |
| `barevalue_estimate` | Calculate cost breakdown for a potential order based on audio duration | `POST /orders/estimate` |

These tools are designed to support the typical workflow pattern where an AI assistant checks available resources before uploading and submitting podcast files for AI editing. By providing cost estimation before submission, users can avoid the `insufficient_credits` error that results from attempting orders without adequate resources.

## Architecture

The Account and Billing module follows a layered architecture where MCP tool definitions in the presentation layer delegate to the API client layer, which handles HTTP communication with the Barevalue API.

```mermaid
graph TD
    A[MCP Client<br>e.g., Claude Code] --> B[Tool Handler<br>src/index.ts]
    B --> C[API Client<br>src/api-client.ts]
    C --> D[Barevalue API<br>barevalue.com/api/v1]
    
    B --> B1[barevalue_account tool]
    B --> B2[barevalue_estimate tool]
    
    C --> C1[getAccount method]
    C --> C2[estimate method]
    
    D --> D1[/account endpoint]
    D --> D2[/orders/estimate endpoint]
    
    B1 -->|"Empty input schema"| B
    B2 -->|"duration_minutes"| B
```

### Data Flow

The following sequence illustrates how account information flows through the system when an AI assistant queries the account status:

```mermaid
sequenceDiagram
    participant Client as MCP Client
    participant Server as MCP Server
    participant APIClient as API Client
    participant API as Barevalue API
    
    Client->>Server: barevalue_account()
    Server->>APIClient: getAccount()
    APIClient->>API: GET /account<br/>Authorization: Bearer <key>
    API-->>APIClient: AccountInfo JSON
    APIClient-->>Server: AccountInfo object
    Server-->>Client: AccountInfo JSON
```

## Tool Specifications

### barevalue_account

The `barevalue_account` tool retrieves complete account information for the authenticated user, including credit balances, AI subscription details, and current pricing information.

#### Input Schema

```json
{
  "type": "object",
  "properties": {},
  "required": []
}
```

This tool accepts no input parameters. The authenticated user is determined by the `BAREVALUE_API_KEY` environment variable configured during server setup. Source: [src/index.ts:30-38](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts#L30-L38)

#### Return Type

The tool returns an `AccountInfo` object containing the following structure:

| Field | Type | Description |
|-------|------|-------------|
| `user` | `User` | User profile information |
| `credits` | `Credits` | Standard credit balance |
| `ai_subscription` | `AISubscription \| null` | AI editing subscription details |
| `ai_bonus_minutes` | `AIBonusMinutes` | Promotional bonus minutes balance |
| `pricing` | `Pricing` | Current pricing information |

Source: [src/types.ts:9-38](https://github.com/quietnotion/barevalue-mcp/blob/main/src/types.ts#L9-L38)

#### User Object

| Field | Type | Description |
|-------|------|-------------|
| `id` | `number` | Unique user identifier |
| `email` | `string` | User's email address |
| `name` | `string \| null` | Display name if set |
| `is_verified` | `boolean` | Whether the account is verified |
| `locale` | `string` | User's preferred locale |

#### Credits Object

| Field | Type | Description |
|-------|------|-------------|
| `balance` | `number` | Available credit amount |
| `currency` | `string` | Currency code (e.g., "USD") |

#### AI Subscription Object

The `ai_subscription` field may be `null` for users without an AI subscription. When present, it contains:

| Field | Type | Description |
|-------|------|-------------|
| `tier` | `string \| null` | Subscription tier name |
| `status` | `string \| null` | Subscription status |
| `minutes_limit` | `number \| null` | Monthly minute allowance |
| `minutes_used` | `number \| null` | Minutes consumed this period |
| `minutes_remaining` | `number \| null` | Minutes left in current period |
| `period_end` | `string \| null` | ISO 8601 end date of billing period |
| `pending_tier` | `string \| null` | Upcoming tier if upgrade is scheduled |

#### AI Bonus Minutes Object

| Field | Type | Description |
|-------|------|-------------|
| `balance` | `number` | Available bonus minutes |
| `expires_at` | `string \| null` | Expiration date for bonus minutes |

#### Pricing Object

| Field | Type | Description |
|-------|------|-------------|
| `audio_per_minute` | `number` | Cost per audio minute (for informational purposes) |
| `currency` | `string` | Currency code |

### barevalue_estimate

The `barevalue_estimate` tool calculates a detailed cost breakdown for a potential podcast editing order based on the audio duration. This tool is essential for preventing `insufficient_credits` errors before submitting orders.

#### Input Schema

```json
{
  "type": "object",
  "properties": {
    "duration_minutes": {
      "type": "number",
      "description": "Audio duration in minutes (1-300)"
    }
  },
  "required": ["duration_minutes"]
}
```

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `duration_minutes` | `number` | Yes | Duration of the audio file in minutes, between 1 and 300 |

Source: [src/index.ts:40-53](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts#L40-L53)

#### Return Type

The tool returns an `EstimateResponse` object:

| Field | Type | Description |
|-------|------|-------------|
| `duration_minutes` | `number` | The requested duration |
| `can_afford` | `boolean` | Whether the user can afford the order |
| `minutes_available` | `MinutesBreakdown` | Available minutes by category |
| `minutes_applied` | `MinutesBreakdown` | Minutes that will be consumed |
| `minutes_remaining_after` | `number` | Total minutes remaining after order |
| `subscription_tier` | `string` | Current subscription tier name |

Source: [src/types.ts:40-66](https://github.com/quietnotion/barevalue-mcp/blob/main/src/types.ts#L40-L66)

#### Conditional Fields

The following fields are only present when `can_afford` is `false`:

| Field | Type | Description |
|-------|------|-------------|
| `minutes_short` | `number` | How many minutes short the user is |
| `upgrade_required` | `boolean` | Whether an upgrade is needed |
| `message` | `string` | Human-readable explanation |
| `available_upgrades` | `UpgradeOption[]` | Available subscription upgrades |

#### Minutes Breakdown Object

Both `minutes_available` and `minutes_applied` contain:

| Field | Type | Description |
|-------|------|-------------|
| `bonus` | `number` | AI bonus minutes |
| `student` | `number` | Student plan minutes (if applicable) |
| `subscription` | `number` | Subscription minutes |
| `total` | `number` | Total minutes |

#### Upgrade Option Object

| Field | Type | Description |
|-------|------|-------------|
| `name` | `string` | Plan name |
| `minutes_limit` | `number` | Monthly minute allowance |
| `price_monthly` | `number` | Monthly price |

## API Client Implementation

The API client layer provides the underlying HTTP communication for the Account and Billing tools. The implementation is located in `src/api-client.ts`.

### getAccount Method

```typescript
async getAccount(): Promise<AccountInfo> {
  return this.request<AccountInfo>('GET', '/account');
}
```

The `getAccount` method performs a simple GET request to the `/account` endpoint, passing the Bearer token authentication header. Source: [src/api-client.ts:180-183](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts#L180-L183)

### estimate Method

```typescript
async estimate(durationMinutes: number): Promise<EstimateResponse> {
  return this.request<EstimateResponse>('POST', '/orders/estimate', {
    duration_minutes: durationMinutes,
  });
}
```

The `estimate` method performs a POST request to the `/orders/estimate` endpoint with the duration parameter in the request body. Source: [src/api-client.ts:186-192](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts#L186-L192)

### HTTP Request Handling

The API client uses Node.js built-in `http` and `https` modules for HTTP communication. Key security features include:

- Bearer token authentication via the `Authorization` header
- HTTPS enforcement warning for non-localhost connections
- JSON request/response handling
- Configurable request timeout (default 5 minutes)
- Comprehensive error handling with structured `BarevalueApiError` responses

## Usage Patterns

### Pre-Order Balance Check

The most common usage pattern involves checking the account balance before submitting a podcast for editing:

```mermaid
graph TD
    A[Start] --> B[Call barevalue_account]
    B --> C{Response received}
    C -->|Success| D[Check credits and minutes]
    C -->|Failure| E[Handle error]
    D --> F{Sufficient resources?}
    F -->|Yes| G[Proceed to upload]
    F -->|No| H[Inform user]
    H --> I[Suggest upgrade or wait]
    G --> J[Upload file]
    J --> K[Submit order]
```

### Pre-Order Cost Estimation

Before uploading a file, users can estimate costs to understand the resource consumption:

```
User: I want to edit a 45-minute podcast episode

Claude: [calls barevalue_estimate duration_minutes=45]

Based on your 45-minute episode:
- Minutes to be used: 45
- Available: 120 minutes (bonus + subscription)
- Remaining after: 75 minutes
- Can afford: Yes
```

### Workflow with Insufficient Credits

When a user lacks sufficient resources, the estimation provides upgrade options:

```
User: Edit this podcast: /path/to/episode.mp3

Claude: [calls barevalue_estimate duration_minutes=32]

Estimate Result:
- Minutes required: 32
- Minutes available: 18
- Short by: 14 minutes

Available upgrades:
| Plan | Monthly Minutes | Price |
|------|-----------------|-------|
| Pro | 60 | $29/mo |
| Team | 150 | $79/mo |

Would you like me to help you upgrade your plan first?
```

## Rate Limits and Security

### Rate Limits

The Account and Billing tools share the global rate limit of the MCP server:

| Limit | Value |
|-------|-------|
| Requests per minute | 10 |

Source: [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

### Security Considerations

The Account and Billing module implements several security measures:

1. **API Key Protection**: The API key is transmitted exclusively via the `Authorization` header using the Bearer token scheme. Source: [src/api-client.ts:63-69](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts#L63-L69)

2. **Environment Variable Storage**: API keys must be stored in environment variables, never hardcoded. This is enforced through the server configuration in `server.json`:

```json
{
  "environmentVariables": [
    {
      "name": "BAREVALUE_API_KEY",
      "isSecret": true,
      "format": "string"
    }
  ]
}
```

Source: [server.json:17-24](https://github.com/quietnotion/barevalue-mcp/blob/main/server.json#L17-L24)

3. **HTTPS Enforcement**: The API client warns users when connecting over non-HTTPS connections (except localhost for development):

```typescript
if (!isHttps && url.hostname !== 'localhost' && url.hostname !== '127.0.0.1') {
  console.error('WARNING: Using non-HTTPS connection. API key may be transmitted insecurely.');
}
```

Source: [src/api-client.ts:42-45](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts#L42-L45)

## Error Handling

The Account and Billing tools may encounter the following errors:

| Error Code | Description | HTTP Status |
|------------|-------------|-------------|
| `invalid_api_key` | API key is missing, invalid, or revoked | 401/403 |
| `rate_limited` | Too many requests (limit: 10/minute) | 429 |
| `server_error` | Internal server error | 500 |

Errors are wrapped in the custom `BarevalueApiError` class, which provides structured error information:

```typescript
export class BarevalueApiError extends Error {
  constructor(
    message: string,
    public readonly code: string,
    public readonly statusCode: number,
    public readonly details?: Record<string, unknown>
  ) {
    super(message);
    this.name = 'BarevalueApiError';
  }
}
```

Source: [src/api-client.ts:238-248](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts#L238-L248)

## Configuration

### Required Environment Variables

| Variable | Required | Description |
|----------|----------|-------------|
| `BAREVALUE_API_KEY` | Yes | Barevalue API key (starts with `bv_sk_`) |
| `BAREVALUE_API_URL` | No | Override API base URL (default: `https://barevalue.com/api/v1`) |

### MCP Server Configuration

To use the Account and Billing tools, configure the MCP server in your Claude Code settings (`~/.claude/settings.json`):

```json
{
  "mcpServers": {
    "barevalue": {
      "command": "npx",
      "args": ["-y", "barevalue-mcp"],
      "env": {
        "BAREVALUE_API_KEY": "bv_sk_your_api_key_here"
      }
    }
  }
}
```

Source: [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Summary

The Account and Billing Tools provide essential functionality for managing Barevalue resources through the MCP interface:

| Component | Description |
|-----------|-------------|
| `barevalue_account` | Retrieves full account information including user details, credit balance, AI subscription status, bonus minutes, and pricing |
| `barevalue_estimate` | Calculates cost breakdown for orders, showing available minutes, consumption by category, and potential upgrade options |
| API Client | Handles HTTP communication with Bearer token authentication, HTTPS enforcement, and structured error handling |

These tools enable AI assistants to perform informed resource management, preventing failed orders due to insufficient credits and providing users with clear visibility into their account status and consumption patterns.

---

<a id='order-workflow'></a>

## Order Workflow Tools

### Related Pages

Related topics: [Account and Billing Tools](#account-tools), [Data Flow](#data-flow), [Webhook Management](#webhook-management)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/index.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)
- [src/types.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/types.ts)
- [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)
- [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)
</details>

# Order Workflow Tools

## Overview

The Order Workflow Tools provide the core functionality for submitting podcast audio files to the Barevalue AI editing service and monitoring their processing status. These tools form the primary interface for the audio editing pipeline, enabling users to upload local files, validate external URLs, submit orders for processing, and track completion.

The workflow consists of six primary MCP tools that handle the complete lifecycle of an editing order from initial upload through final delivery. Each tool corresponds to specific API endpoints in the underlying `BarevalueApiClient` class, which manages HTTP communication with the Barevalue API.

Source: [src/index.ts:36-170](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

## Architecture

```mermaid
graph TD
    A[User] --> B[barevalue_upload<br/>or barevalue_validate]
    B --> C{File Source}
    C -->|Local File| D[Get Presigned S3 URL]
    C -->|External URL| E[Validate File]
    D --> F[Upload to S3]
    E --> G{Validation Result}
    G -->|Pass| H[barevalue_submit<br/>or barevalue_submit_url]
    G -->|Fail| Z[Error: validation_failed]
    F --> H
    H --> I[Order Created<br/>Status: pending]
    I --> J[barevalue_status]
    J --> K{Processing State}
    K -->|pending| L[Downloading]
    K -->|processing| M[Transcribing<br/>+ Editing]
    K -->|completed| N[Deliverables Ready]
    K -->|failed| O[Error Response]
    N --> P[barevalue_list_orders<br/>for history]
```

The `BarevalueApiClient` class encapsulates all API interactions and provides type-safe methods for each endpoint. It handles authentication via Bearer tokens, manages request timeouts, and implements error handling with custom `BarevalueApiError` exceptions.

Source: [src/api-client.ts:1-80](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

## File Upload Tool

### barevalue_upload

Uploads a local audio file to S3 storage using a presigned URL mechanism. This tool handles the two-step upload process: first requesting a presigned URL from the API, then uploading the file directly to S3.

**Input Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `file_path` | `string` | Yes | Absolute path to the local audio file |

**Returns:**

| Field | Type | Description |
|-------|------|-------------|
| `order_id` | `number` | Numeric identifier for tracking |
| `s3_key` | `string` | S3 storage key for submission |
| `upload_url` | `string` | Presigned URL for direct upload |

**Supported Formats:** mp3, wav, m4a, flac, aac, ogg

**Maximum File Size:** 750MB

Source: [src/index.ts:66-80](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)
Source: [src/api-client.ts:145-180](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

### Content Type Mapping

The client automatically detects file format from extension and sets appropriate MIME types:

| Extension | Content-Type |
|-----------|--------------|
| `.mp3` | audio/mpeg |
| `.wav` | audio/wav |
| `.m4a` | audio/mp4 |
| `.flac` | audio/flac |
| `.aac` | audio/aac |
| `.ogg` | audio/ogg |
| `.wma` | audio/x-ms-wma |
| `.aiff` / `.aif` | audio/aiff |

Source: [src/api-client.ts:195-210](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

## File Validation Tool

### barevalue_validate

Performs pre-submission validation on files hosted at external URLs. This tool checks speech content percentage and detects music-only files without consuming credits.

**Input Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `file_url` | `string` | Yes | Public URL to the audio file |

**Returns:**

| Field | Type | Description |
|-------|------|-------------|
| `valid` | `boolean` | Whether the file passes validation |
| `speech_detected` | `number` | Percentage of speech content (minimum 10% required) |
| `music_only` | `boolean` | Whether music-only content was detected |
| `duration_minutes` | `number` | Total audio duration |

**Note:** This tool is for external URLs only. Files uploaded via `barevalue_upload` do not require validation.

Source: [src/index.ts:82-95](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)
Source: [README.md:85-95](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

```mermaid
graph LR
    A[External URL] --> B[POST /orders/validate]
    B --> C{Validation Rules}
    C -->|Speech ≥ 10%| D[✓ Valid]
    C -->|Speech < 10%| E[✗ validation_failed]
    C -->|Music only| E
```

## Order Submission Tools

### barevalue_submit

Submits an order for processing using a file previously uploaded via `barevalue_upload`. This is the final step that triggers the AI editing pipeline.

**Input Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `order_id` | `number` | Yes | Order ID from upload step |
| `s3_key` | `string` | Yes | S3 key from upload step |
| `podcast_name` | `string` | Yes | Name of the podcast |
| `episode_name` | `string` | Yes | Name of this episode |
| `episode_number` | `string` | No | Episode number for organization |
| `special_instructions` | `string` | No | Custom editing instructions (max 2000 chars) |
| `processing_style` | `string` | No | `standard`, `minimal`, or `aggressive` |
| `host_names` | `string[]` | No | Array of host names (max 5) |
| `guest_names` | `string[]` | No | Array of guest names (max 10) |

Source: [src/index.ts:97-130](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

**Processing Styles:**

| Style | Description |
|-------|-------------|
| `standard` | Default editing level |
| `minimal` | Light editing, preserves more original content |
| `aggressive` | Heavy editing, removes more filler |

### barevalue_submit_url

Submits an order directly from an external URL without requiring a separate upload step. Combines validation and submission in one operation.

**Input Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `file_url` | `string` | Yes | Public URL to the audio file |
| `podcast_name` | `string` | Yes | Name of the podcast |
| `episode_name` | `string` | Yes | Name of this episode |
| `episode_number` | `string` | No | Episode number |
| `special_instructions` | `string` | No | Custom editing instructions |
| `processing_style` | `string` | No | `standard`, `minimal`, or `aggressive` |
| `host_names` | `string[]` | No | Host names for speaker labels |
| `guest_names` | `string[]` | No | Guest names for speaker labels |

**Response Fields:**

| Field | Type | Description |
|-------|------|-------------|
| `order_id` | `number` | Assigned order identifier |
| `status` | `string` | Current order status |
| `cost_breakdown` | `object` | AI minutes, credits, and payment details |
| `estimated_completion` | `string` | ISO timestamp for expected completion |

Source: [src/types.ts:45-60](https://github.com/quietnotion/barevalue-mcp/blob/main/src/types.ts)

## Order Status Tools

### barevalue_status

Retrieves the current processing state of an order and provides download URLs when processing is complete.

**Input Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `order_id` | `number` | Yes | Order ID to check |

**Order Status Values:**

| Status | Description |
|--------|-------------|
| `pending` | Order received, awaiting download |
| `downloading` | Fetching source file from S3/URL |
| `processing` | Initial processing phase |
| `transcribing` | Converting speech to text |
| `editing` | AI editing in progress |
| `completed` | Processing finished, deliverables ready |
| `failed` | Processing error occurred |
| `refunded` | Order was refunded |

Source: [src/types.ts:62-80](https://github.com/quietnotion/barevalue-mcp/blob/main/src/types.ts)

**Response with Downloads (when completed):**

| Field | Type | Description |
|-------|------|-------------|
| `order_id` | `number` | Order identifier |
| `status` | `string` | Current status |
| `podcast_name` | `string` | Podcast name |
| `episode_name` | `string` | Episode name |
| `duration_minutes` | `number` | Audio duration |
| `downloads.edited_audio` | `string` | URL to edited audio file |
| `downloads.transcript_pdf` | `string` | URL to PDF transcript |
| `downloads.transcript_docx` | `string` | URL to Word transcript |
| `downloads.show_notes` | `string` | URL to show notes (nullable) |
| `error` | `object` | Error details if failed |

Source: [src/index.ts:132-150](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

### barevalue_list_orders

Retrieves a paginated list of recent orders with optional status filtering.

**Input Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `page` | `number` | No | 1 | Page number |
| `per_page` | `number` | No | 20 | Results per page (max 100) |
| `status` | `string` | No | - | Filter: `pending`, `processing`, `completed`, `failed` |

**Response Structure:**

| Field | Type | Description |
|-------|------|-------------|
| `orders` | `OrderListItem[]` | Array of order summaries |
| `pagination.page` | `number` | Current page |
| `pagination.per_page` | `number` | Items per page |
| `pagination.total` | `number` | Total matching orders |
| `pagination.total_pages` | `number` | Total pages available |

**Order List Item Fields:**

| Field | Type | Description |
|-------|------|-------------|
| `order_id` | `number` | Order identifier |
| `status` | `string` | Current status |
| `podcast_name` | `string` | Podcast name |
| `episode_name` | `string` | Episode name |
| `duration_minutes` | `number` | Audio duration |
| `created_at` | `string` | ISO timestamp |
| `completed_at` | `string` | ISO timestamp or null |

Source: [src/index.ts:152-175](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)
Source: [src/types.ts:82-95](https://github.com/quietnotion/barevalue-mcp/blob/main/src/types.ts)

## Complete Workflow Patterns

### Local File Workflow

```mermaid
sequenceDiagram
    participant User
    participant MCP as barevalue-mcp
    participant API as Barevalue API
    participant S3 as AWS S3

    User->>MCP: barevalue_upload(file_path)
    MCP->>API: GET /orders/upload-url
    API->>S3: Generate presigned URL
    S3-->>API: Presigned URL
    API-->>MCP: {order_id, s3_key, upload_url}
    MCP->>S3: PUT file to presigned URL
    S3-->>MCP: 200 OK
    MCP-->>User: {order_id, s3_key}

    User->>MCP: barevalue_submit(params)
    MCP->>API: POST /orders/submit
    API-->>MCP: {order_id, status, estimated_completion}
    MCP-->>User: Order submitted

    loop Poll until completed
        User->>MCP: barevalue_status(order_id)
        MCP->>API: GET /orders/{id}
        API-->>MCP: {status, downloads?}
        MCP-->>User: Current status
    end
```

### External URL Workflow

```mermaid
sequenceDiagram
    participant User
    participant MCP as barevalue-mcp
    participant API as Barevalue API

    User->>MCP: barevalue_validate(file_url)
    MCP->>API: POST /orders/validate
    API-->>MCP: {valid, speech_detected, duration}
    MCP-->>User: Validation result

    alt Validation passed
        User->>MCP: barevalue_submit_url(params)
        MCP->>API: POST /orders/submit
        API-->>MCP: {order_id, status}
        MCP-->>User: Order submitted
    else Validation failed
        MCP-->>User: Error: validation_failed
    end
```

## Error Handling

The API client throws `BarevalueApiError` for failed requests with structured error responses:

```typescript
export class BarevalueApiError extends Error {
  constructor(
    message: string,
    public readonly code: string,
    public readonly statusCode: number,
    public readonly details?: Record<string, unknown>
  ) {
    super(message);
    this.name = 'BarevalueApiError';
  }
}
```

**Common Error Codes:**

| Error Code | HTTP Status | Description |
|------------|-------------|-------------|
| `invalid_api_key` | 401 | API key missing, invalid, or revoked |
| `insufficient_credits` | 402 | Not enough credits or subscription minutes |
| `validation_failed` | 400 | File failed pre-checks (insufficient speech or music-only) |
| `file_too_large` | 413 | File exceeds 750MB limit |
| `rate_limited` | 429 | Too many requests (limit: 10/minute) |

Source: [src/api-client.ts:90-120](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)
Source: [README.md:55-65](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Rate Limits

| Limit | Value |
|-------|-------|
| Requests per minute | 10 per API key |
| File upload timeout | 5 minutes |
| Order processing | 10-30 minutes typical |

## Security Considerations

The API client implements several security measures:

1. **API Key Validation**: Keys must start with `bv_sk_` prefix
2. **HTTPS Enforcement**: Warns when using non-HTTPS for non-localhost connections
3. **S3 Upload Security**: Presigned URLs expire after 30 minutes
4. **Error Sanitization**: Raw API responses are not exposed in error messages
5. **Timeout Protection**: All requests have configurable timeouts

Source: [src/api-client.ts:40-60](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

---

<a id='webhook-management'></a>

## Webhook Management

### Related Pages

Related topics: [Order Workflow Tools](#order-workflow), [Error Handling and Rate Limits](#error-handling)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)
- [src/index.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)
- [src/types.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/types.ts)
- [test-webhooks.js](https://github.com/quietnotion/barevalue-mcp/blob/main/test-webhooks.js)
- [server.json](https://github.com/quietnotion/barevalue-mcp/blob/main/server.json)
- [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)
</details>

# Webhook Management

## Overview

Webhook Management in barevalue-mcp provides a comprehensive system for subscribing to and receiving real-time notifications about order lifecycle events. The MCP server exposes five distinct webhook management tools that allow clients to create, read, update, delete, and rotate secrets for webhooks configured against the Barevalue API.

Webhooks serve as the primary mechanism for asynchronous order status notifications. When orders complete, fail, or are refunded, the Barevalue API delivers signed HTTP POST payloads to registered webhook endpoints, enabling automated downstream processing without polling. Source: [src/api-client.ts:109-134]()

## Architecture

### Component Overview

The webhook management system consists of three primary layers:

1. **API Client Layer** (`BarevalueApiClient`) - Handles HTTP communication with the Barevalue API
2. **Tool Definition Layer** (`src/index.ts`) - Exposes MCP-compatible tool interfaces
3. **Type System** (`src/types.ts`) - Provides TypeScript interfaces for type safety

### Data Flow

```mermaid
graph TD
    A[MCP Client] -->|barevalue_webhook_*| B[barevalue-mcp Server]
    B -->|HTTP Request| C[Barevalue API]
    C -->|Webhook Payload| D[Client Endpoint]
    D -->|HMAC Verification| E[Process Event]
    
    F[Order Events] -->|triggers| C
    G[order.completed] --> F
    H[order.failed] --> F
    I[order.refunded] --> F
```

### Tool-to-API Mapping

| MCP Tool | HTTP Method | API Endpoint | Source |
|----------|-------------|--------------|--------|
| `barevalue_webhooks_list` | GET | `/webhooks` | [src/index.ts:89-97]() |
| `barevalue_webhook_create` | POST | `/webhooks` | [src/index.ts:99-123]() |
| `barevalue_webhook_update` | PATCH | `/webhooks/{id}` | [src/index.ts:125-151]() |
| `barevalue_webhook_delete` | DELETE | `/webhooks/{id}` | [src/index.ts:153-167]() |
| `barevalue_webhook_rotate_secret` | POST | `/webhooks/{id}/rotate-secret` | [src/index.ts:169-189]() |

## Available Webhook Events

The Barevalue API supports three distinct event types that clients can subscribe to:

| Event | Description | Trigger Condition |
|-------|-------------|-------------------|
| `order.completed` | Order finished processing | AI editing completed successfully |
| `order.failed` | Order processing failed | Error during processing or validation |
| `order.refunded` | Order was refunded | Credit reversal processed |

Source: [src/index.ts:108-112]()

## Data Models

### Webhook Interface

```typescript
interface Webhook {
  id: number;
  url: string;
  events: string[];
  is_active: boolean;
  failure_count: number;
  last_triggered_at: string | null;
  created_at: string;
  secret?: string; // Only returned on create
}
```

Source: [src/types.ts:67-76]()

### WebhookListResponse Interface

```typescript
interface WebhookListResponse {
  webhooks: Webhook[];
}
```

Source: [src/types.ts:78-80]()

### Input Type Definitions

```typescript
interface WebhookCreateInput {
  url: string;
  events: string[];
}

interface WebhookUpdateInput {
  webhook_id: number;
  url?: string;
  events?: string[];
  is_active?: boolean;
}

interface WebhookDeleteInput {
  webhook_id: number;
}

interface WebhookRotateSecretInput {
  webhook_id: number;
}
```

Source: [src/types.ts:121-143]()

## Tool Specifications

### List Webhooks

Retrieves all configured webhooks for the authenticated account.

**Tool Name:** `barevalue_webhooks_list`

**Input Schema:**
```json
{
  "type": "object",
  "properties": {},
  "required": []
}
```

**Behavior:** Returns an array of all webhooks including their URLs, subscribed events, active status, failure counts, and timestamps. The `secret` field is omitted for security reasons. Source: [src/index.ts:89-97]()

### Create Webhook

Registers a new webhook endpoint to receive event notifications.

**Tool Name:** `barevalue_webhook_create`

**Input Schema:**
```json
{
  "type": "object",
  "properties": {
    "url": {
      "type": "string",
      "description": "HTTPS URL to receive webhook payloads"
    },
    "events": {
      "type": "array",
      "items": {
        "type": "string",
        "enum": ["order.completed", "order.failed", "order.refunded"]
      },
      "description": "Events to subscribe to"
    }
  },
  "required": ["url", "events"]
}
```

**Response Note:** The `secret` field is returned only on creation and is displayed with a warning to save it immediately. The secret is never shown again. Source: [src/index.ts:227-237]()

### Update Webhook

Modifies an existing webhook's configuration.

**Tool Name:** `barevalue_webhook_update`

**Input Schema:**
```json
{
  "type": "object",
  "properties": {
    "webhook_id": {
      "type": "number",
      "description": "Webhook ID to update"
    },
    "url": {
      "type": "string",
      "description": "New HTTPS URL"
    },
    "events": {
      "type": "array",
      "items": { "type": "string" },
      "description": "New events list"
    },
    "is_active": {
      "type": "boolean",
      "description": "Enable or disable the webhook"
    }
  },
  "required": ["webhook_id"]
}
```

**Behavior:** All update fields are optional. Only provided fields are sent to the API. The webhook ID must be specified to identify the target webhook. Source: [src/index.ts:239-249]()

### Delete Webhook

Permanently removes a webhook configuration.

**Tool Name:** `barevalue_webhook_delete`

**Input Schema:**
```json
{
  "type": "object",
  "properties": {
    "webhook_id": {
      "type": "number",
      "description": "Webhook ID to delete"
    }
  },
  "required": ["webhook_id"]
}
```

**Warning:** This operation is irreversible. The webhook is deleted immediately and cannot be recovered. Source: [src/index.ts:153-167]()

### Rotate Webhook Secret

Generates a new HMAC signing secret for webhook payload verification.

**Tool Name:** `barevalue_webhook_rotate_secret`

**Input Schema:**
```json
{
  "type": "object",
  "properties": {
    "webhook_id": {
      "type": "number",
      "description": "Webhook ID to rotate secret for"
    }
  },
  "required": ["webhook_id"]
}
```

**Behavior:** Immediately invalidates the previous secret. The new secret is returned once and cannot be retrieved again. Clients must update their webhook handlers with the new secret before the rotation is performed. Source: [src/index.ts:251-261]()

## Security

### Signature Verification

Webhook payloads are signed using HMAC-SHA256 to ensure authenticity and integrity. The signature is included in the `X-Barevalue-Signature` header of each webhook request. Source: [README.md:143-145]()

**Verification Process:**
```mermaid
graph LR
    A[Receive Payload] --> B[Extract Signature Header]
    B --> C[Compute HMAC-SHA256]
    C --> D[Compare with Header]
    D -->|Match| E[Process Payload]
    D -->|Mismatch| F[Reject Request]
```

### Secret Management

| Operation | Secret Behavior |
|-----------|-----------------|
| Create | Secret generated and returned (one-time view) |
| List | Secret omitted from response |
| Update | Secret unchanged |
| Rotate | New secret generated, old immediately invalid |
| Delete | Secret destroyed |

### Presigned URL Security

Presigned S3 URLs for order downloads expire after 30 minutes. Webhook secrets follow the same security model with immediate invalidation upon rotation. Source: [README.md:143-145]()

## API Client Implementation

### Webhook Methods in BarevalueApiClient

```typescript
// List all webhooks
async listWebhooks(): Promise<WebhookListResponse> {
  return this.request<WebhookListResponse>('GET', '/webhooks');
}

// Create a webhook
async createWebhook(url: string, events: string[]): Promise<Webhook> {
  return this.request<Webhook>('POST', '/webhooks', { url, events });
}

// Get a specific webhook
async getWebhook(webhookId: number): Promise<Webhook> {
  return this.request<Webhook>('GET', `/webhooks/${webhookId}`);
}

// Update a webhook
async updateWebhook(
  webhookId: number,
  updates: { url?: string; events?: string[]; is_active?: boolean }
): Promise<Webhook> {
  return this.request<Webhook>('PATCH', `/webhooks/${webhookId}`, updates);
}

// Delete a webhook
async deleteWebhook(webhookId: number): Promise<{ success: boolean }> {
  return this.request<{ success: boolean }>('DELETE', `/webhooks/${webhookId}`);
}

// Rotate webhook secret
async rotateWebhookSecret(webhookId: number): Promise<Webhook> {
  return this.request<Webhook>('POST', `/webhooks/${webhookId}/rotate-secret`);
}
```

Source: [src/api-client.ts:109-134]()

### HTTP Request Configuration

The API client uses Node.js native `http` and `https` modules with the following security headers:

```typescript
const options: https.RequestOptions = {
  hostname: url.hostname,
  port: url.port || (isHttps ? 443 : 80),
  path: url.pathname + url.search,
  method,
  headers: {
    'Authorization': `Bearer ${this.apiKey}`,
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'User-Agent': 'barevalue-mcp/1.0.0',
  },
  timeout: this.timeout,
};
```

Source: [src/api-client.ts:48-70]()

## Testing

### Integration Test Coverage

The repository includes a comprehensive test suite for webhook operations in `test-webhooks.js`. Tests verify:

| Test | Operation | Assertions |
|------|-----------|------------|
| 1 | Create Webhook | Returns `id`, `secret`, validates response structure |
| 2 | Update Webhook | Event list updates to 3 items |
| 3 | Rotate Secret | New secret differs from original |
| 4 | Delete Webhook | Successful deletion confirmation |

Source: [test-webhooks.js:20-90]()

### Test Execution Flow

```mermaid
graph TD
    A[Start Test Server] --> B[Create Webhook]
    B -->|wait 2s| C[Update Webhook]
    C -->|wait 2s| D[Rotate Secret]
    D -->|wait 2s| E[Delete Webhook]
    E --> F[Print Results]
    
    B -->|success| G[passed++]
    C -->|success| G
    D -->|success| G
    E -->|success| G
    
    B -->|failure| H[failed++]
    C -->|failure| H
    D -->|failure| H
    E -->|failure| H
```

### Test Output Example

```
1. Create Webhook... ✅
   Response: {
     "id": 123,
     "url": "https://httpbin.org/post",
     "events": ["order.completed", "order.failed"],
     "secret": "whsec_..."
   }

2. Update Webhook... ✅
   Response: {
     "id": 123,
     "events": ["order.completed", "order.failed", "order.refunded"]
   }

3. Rotate Webhook Secret... ✅
   Response: { "id": 123, "secret": "whsec_new..." }

4. Delete Webhook... ✅
   Response: { "success": true }

=== Results ===
Passed: 4
Failed: 0
Webhook operations: 100% verified ✅
```

## Error Handling

### API Error Response Format

```typescript
class BarevalueApiError extends Error {
  constructor(
    message: string,
    public readonly code: string,
    public readonly statusCode: number,
    public readonly details?: Record<string, unknown>
  ) {
    super(message);
    this.name = 'BarevalueApiError';
  }
}
```

Source: [src/api-client.ts:86-94]()

### Common Error Codes

| HTTP Status | Error Code | Description |
|-------------|------------|-------------|
| 400 | `invalid_request` | Malformed request body |
| 401 | `invalid_api_key` | Missing or invalid API key |
| 404 | `not_found` | Webhook ID does not exist |
| 422 | `validation_failed` | Invalid URL or events format |
| 429 | `rate_limited` | Exceeded rate limit (10/minute) |
| 500 | `internal_error` | Server-side error |

### Error Sanitization

The MCP server sanitizes all error responses to prevent leakage of sensitive data:

```typescript
return {
  content: [{
    type: 'text',
    text: JSON.stringify({
      error: error.code,
      message: sanitizeString(error.message),
      statusCode: error.statusCode,
      details: sanitizeData(error.details),
    }, null, 2)
  }]
};
```

Source: [src/index.ts:275-292]()

## Usage Examples

### Complete Webhook Lifecycle

```javascript
// 1. Create a webhook
const webhook = await callTool('barevalue_webhook_create', {
  url: 'https://your-server.com/webhooks/barevalue',
  events: ['order.completed', 'order.failed', 'order.refunded']
});
// Save webhook.secret securely - only shown once!

// 2. List webhooks to verify
const webhooks = await callTool('barevalue_webhooks_list');
console.log('Configured webhooks:', webhooks.webhooks.length);

// 3. Update webhook to disable during maintenance
await callTool('barevalue_webhook_update', {
  webhook_id: webhook.id,
  is_active: false
});

// 4. Re-enable and rotate secret periodically
await callTool('barevalue_webhook_update', {
  webhook_id: webhook.id,
  is_active: true
});

const newWebhook = await callTool('barevalue_webhook_rotate_secret', {
  webhook_id: webhook.id
});
// Update your server with newWebhook.secret

// 5. Delete when no longer needed
await callTool('barevalue_webhook_delete', {
  webhook_id: webhook.id
});
```

### Handling Webhook Payloads

```javascript
// Example webhook handler (server-side)
const crypto = require('crypto');

function handleWebhook(payload, signature, secret) {
  // Verify signature
  const expectedSig = crypto
    .createHmac('sha256', secret)
    .update(JSON.stringify(payload))
    .digest('hex');
  
  if (signature !== expectedSig) {
    return { error: 'Invalid signature', status: 401 };
  }
  
  // Process based on event type
  switch (payload.event) {
    case 'order.completed':
      downloadEditedAudio(payload.order_id);
      break;
    case 'order.failed':
      notifySupport(payload.order_id, payload.error);
      break;
    case 'order.refunded':
      updateCredits(payload.account_id, payload.amount);
      break;
  }
  
  return { status: 200 };
}
```

## Configuration

### Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `BAREVALUE_API_KEY` | Yes | - | API key with `bv_sk_` prefix |
| `BAREVALUE_API_URL` | No | `https://barevalue.com/api/v1` | Override API base URL |

Source: [server.json:16-22]()

### MCP Server Registration

```json
{
  "mcpServers": {
    "barevalue": {
      "command": "npx",
      "args": ["-y", "barevalue-mcp"],
      "env": {
        "BAREVALUE_API_KEY": "bv_sk_your_api_key_here"
      }
    }
  }
}
```

## Rate Limits

Webhook management operations are subject to the following limits:

| Limit | Value | Scope |
|-------|-------|-------|
| API Requests | 10/minute | Per API key |
| File Uploads | 5-minute timeout | Per upload |
| Webhook Delivery | Best effort | Per endpoint |

Source: [README.md:147-150]()

## See Also

- [Account & Billing](README.md#account--billing) - Check credits before webhook-triggered operations
- [Order Workflow](README.md#order-workflow) - Understand order lifecycle events
- [Security](README.md#security) - General security practices

---

<a id='error-handling'></a>

## Error Handling and Rate Limits

### Related Pages

Related topics: [Account and Billing Tools](#account-tools), [Order Workflow Tools](#order-workflow)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/index.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)
- [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)
- [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)
- [src/types.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/types.ts)
</details>

# Error Handling and Rate Limits

The barevalue-mcp server implements comprehensive error handling and rate limiting mechanisms to ensure reliable communication with the Barevalue API while protecting against misuse and providing meaningful feedback to clients.

## Overview

The error handling system in barevalue-mcp serves three primary purposes:

1. **API Error Propagation** - Translating Barevalue API errors into structured, actionable responses
2. **Client-Side Validation** - Catching issues before they reach the API (format validation, file size limits)
3. **Security Enforcement** - Preventing sensitive data exposure and flagging insecure configurations

Rate limiting controls resource consumption and ensures fair access to the Barevalue API infrastructure.

## Error Architecture

### Error Class Hierarchy

The `BarevalueApiError` class extends the standard `Error` type with additional context specific to API failures:

```typescript
export class BarevalueApiError extends Error {
  constructor(
    message: string,
    public readonly code: string,
    public readonly statusCode: number,
    public readonly details?: Record<string, unknown>
  ) {
    super(message);
    this.name = 'BarevalueApiError';
  }

  toJSON() {
    return {
      error: this.code,
      message: this.message,
      statusCode: this.statusCode,
      details: this.details
    };
  }
}
```

**Source:** [src/api-client.ts:180-195](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts#L180-L195)

### Error Response Flow

```mermaid
graph TD
    A[API Request] --> B{HTTP Status Code}
    B -->|2xx| C[Parse JSON Response]
    B -->|4xx/5xx| D[Create BarevalueApiError]
    C -->|Parse Success| E[Return Data]
    C -->|Parse Failure| F[Create Generic Error]
    D --> G[Return Error to Client]
    E --> H[Return Data to Client]
    F --> G
```

## Common Error Codes

The Barevalue API returns structured error responses with standardized error codes:

| Error Code | HTTP Status | Description | Resolution |
|------------|-------------|-------------|------------|
| `invalid_api_key` | 401 | API key missing, invalid format, or revoked | Verify API key starts with `bv_sk_` and is active |
| `insufficient_credits` | 402 | Not enough credits or subscription minutes | Check account balance, upgrade plan if needed |
| `validation_failed` | 400 | File failed pre-checks (insufficient speech, music-only detected) | Ensure audio has >10% speech content |
| `file_too_large` | 413 | File exceeds 750MB limit | Compress or split the audio file |
| `rate_limited` | 429 | Too many requests | Wait before retrying (limit: 10/minute) |
| `unknown_error` | varies | Unhandled server error | Contact support with error details |

**Source:** [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

### Error Response Structure

API errors are returned with the following JSON structure:

```json
{
  "error": "error_code",
  "message": "Human-readable error description",
  "statusCode": 402,
  "details": {
    "current_balance": 0,
    "required_credits": 3.15,
    "has_subscription": true
  }
}
```

**Source:** [src/api-client.ts:100-108](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts#L100-L108)

## Input Validation

### API Key Format Validation

The server validates API key format before making any requests:

```typescript
if (!this.apiKey.startsWith('bv_sk_')) {
  throw new Error(
    'Invalid API key format. Barevalue API keys must start with "bv_sk_".'
  );
}
```

**Source:** [src/api-client.ts:30-34](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts#L30-L34)

### Security Warnings

Non-HTTPS connections trigger console warnings to prevent insecure key transmission:

```typescript
const url = new URL(this.baseUrl);
const isHttps = url.protocol === 'https:';
if (!isHttps && url.hostname !== 'localhost' && url.hostname !== '127.0.0.1') {
  console.error('WARNING: Using non-HTTPS connection. API key may be transmitted insecurely.');
}
```

**Source:** [src/api-client.ts:35-39](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts#L35-L39)

### Content-Type Detection

File uploads use extension-based content type detection:

| Extension | MIME Type |
|-----------|-----------|
| `.mp3` | audio/mpeg |
| `.wav` | audio/wav |
| `.m4a` | audio/mp4 |
| `.flac` | audio/flac |
| `.aac` | audio/aac |
| `.ogg` | audio/ogg |
| `.wma` | audio/x-ms-wma |
| `.aiff` / `.aif` | audio/aiff |

Unknown extensions default to `application/octet-stream`.

**Source:** [src/api-client.ts:165-178](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts#L165-L178)

## Timeout Configuration

### Request Timeouts

All HTTP requests are subject to timeout constraints to prevent hanging connections:

| Operation | Timeout | Behavior on Expiry |
|-----------|---------|-------------------|
| Standard API requests | Default HTTP timeout | Request destroyed, error thrown |
| S3 file uploads | Upload timeout | Request destroyed, error thrown |

```typescript
req.on('timeout', () => {
  req.destroy();
  reject(new Error('API request timed out'));
});
```

**Source:** [src/api-client.ts:113-115](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts#L113-L115)

### Timeout Error Handling

Both S3 upload and API request handlers implement consistent timeout behavior:

```typescript
req.on('timeout', () => {
  req.destroy();
  reject(new Error('S3 upload timed out'));
});
```

**Source:** [src/api-client.ts:144-146](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts#L144-L146)

## Security Measures

### Data Sanitization

Error messages are sanitized before being returned to clients to prevent information leakage:

```typescript
function sanitizeData(data: unknown): unknown {
  if (typeof data === 'string') {
    return sanitizeString(data);
  }
  if (Array.isArray(data)) {
    return data.map(sanitizeData);
  }
  if (data !== null && typeof data === 'object') {
    const result: Record<string, unknown> = {};
    for (const [key, value] of Object.entries(data)) {
      result[sanitizeString(key)] = sanitizeData(value);
    }
    return result;
  }
  return data;
}
```

**Source:** [src/index.ts:1-18](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts#L1-L18)

### Error Response Protection

S3 upload errors do not expose raw response data to prevent leaking internal implementation details:

```typescript
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
  resolve();
} else {
  // Security: Don't expose S3 error response data
  reject(new Error(`S3 upload failed with status ${res.statusCode}`));
}
```

**Source:** [src/api-client.ts:140-143](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts#L140-L143)

### API Response Parsing Protection

Malformed API responses are handled without exposing raw data:

```typescript
try {
  const parsed = JSON.parse(data);
  // ... process response
} catch {
  // Security: Don't expose raw API response data in error messages
  reject(new Error('Failed to parse API response'));
}
```

**Source:** [src/api-client.ts:100-108](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts#L100-L108)

## Rate Limiting

### API Rate Limits

The Barevalue API enforces the following rate limits:

| Limit Type | Value | Scope |
|------------|-------|-------|
| Requests per minute | 10 | Per API key |
| File upload timeout | 5 minutes | Per upload |
| Order processing | 10-30 minutes | Per order |

**Source:** [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

### Rate Limit Handling

When rate limited, the API returns a `429 Too Many Requests` response:

```json
{
  "error": "rate_limited",
  "message": "Too many requests. Please wait before retrying.",
  "statusCode": 429
}
```

Clients should implement exponential backoff when encountering rate limits.

## Error Handling in Tool Calls

### Tool Execution Error Flow

All tool calls are wrapped in try-catch blocks that sanitize errors before returning responses:

```typescript
try {
  // Tool execution logic
  const result = await executeTool(args);
  return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
} catch (error) {
  return {
    content: [
      {
        type: 'text',
        text: JSON.stringify(
          {
            error: 'tool_error',
            message: sanitizeString(error instanceof Error ? error.message : 'Unknown error occurred'),
          },
          null,
          2
        ),
      },
    ],
  };
}
```

**Source:** [src/index.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

### Error Response Format

Tool errors are always returned in a consistent format:

```json
{
  "error": "tool_error",
  "message": "Sanitized error message without sensitive data"
}
```

## Webhook Security

### HMAC-SHA256 Verification

Webhook payloads use HMAC-SHA256 signatures for verification:

> Webhook signatures use HMAC-SHA256 for verification

**Source:** [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

### Secret Rotation

Webhooks support secret rotation to maintain security without service interruption:

```typescript
async rotateWebhookSecret(webhookId: number): Promise<Webhook> {
  return this.request<Webhook>('POST', `/webhooks/${webhookId}/rotate-secret`);
}
```

**Source:** [src/api-client.ts:175-178](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts#L175-L178)

### Presigned URL Expiration

S3 presigned URLs expire after 30 minutes for security:

> Presigned S3 URLs expire after 30 minutes

**Source:** [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Best Practices

### Client-Side Error Handling

1. **Always check the `error` field** in responses before processing data
2. **Implement retry logic** with exponential backoff for transient errors
3. **Monitor rate limits** by tracking request counts per API key
4. **Validate files locally** before upload (format, size, speech content)

### Error Recovery Strategies

| Error Type | Recommended Action |
|------------|-------------------|
| `invalid_api_key` | Verify key format and regenerate if needed |
| `insufficient_credits` | Check account balance or upgrade plan |
| `validation_failed` | Pre-validate audio with `barevalue_validate` tool |
| `rate_limited` | Wait and retry with exponential backoff |
| Network timeout | Retry once, then investigate connectivity |

### Security Checklist

- [ ] API keys stored in environment variables, never hardcoded
- [ ] HTTPS used for all non-localhost connections
- [ ] Error responses sanitized before logging
- [ ] Webhook signatures verified on receipt
- [ ] Presigned URLs used within 30-minute window

---

<a id='security'></a>

## Security

### Related Pages

Related topics: [Configuration Reference](#configuration), [Webhook Management](#webhook-management)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)
- [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)
- [src/index.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)
- [server.json](https://github.com/quietnotion/barevalue-mcp/blob/main/server.json)
- [src/types.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/types.ts)
- [package.json](https://github.com/quietnotion/barevalue-mcp/blob/main/package.json)
</details>

# Security

This page documents the security architecture, measures, and best practices implemented in the barevalue-mcp project. The barevalue-mcp is a Model Context Protocol (MCP) server that enables programmatic interaction with the Barevalue AI podcast editing API.

## Overview

The barevalue-mcp server implements multiple layers of security to protect sensitive data during API communication. The primary security concerns include:

- **API Key Protection**: Preventing exposure of authentication credentials
- **Transport Security**: Ensuring encrypted communication channels
- **Input Sanitization**: Protecting against injection attacks
- **Error Handling**: Avoiding information leakage in error messages
- **Webhook Security**: Verifying authenticity of incoming webhook requests

Source: [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Environment Variables

Environment variables are the sole mechanism for configuring sensitive credentials. The server does not support hardcoded values or configuration files for secrets.

| Variable | Required | Type | Description |
|----------|----------|------|-------------|
| `BAREVALUE_API_KEY` | Yes | String | Your Barevalue API key. Must start with `bv_sk_`. Marked as secret in MCP configuration. |
| `BAREVALUE_API_URL` | No | String | Override API base URL. Defaults to `https://barevalue.com/api/v1` |

Source: [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md), [server.json](https://github.com/quietnotion/barevalue-mcp/blob/main/server.json)

## API Key Protection

### Format Validation

The API client validates the format of incoming API keys to ensure they conform to the expected pattern. Keys must begin with the `bv_sk_` prefix.

```typescript
if (!this.apiKey.startsWith('bv_sk_')) {
  throw new Error(
    'Invalid API key format. Barevalue API keys must start with "bv_sk_".'
  );
}
```

Source: [src/api-client.ts:1-100](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

### Secret Handling

The `BAREVALUE_API_KEY` environment variable is declared as a secret in the MCP server configuration:

```json
{
  "name": "BAREVALUE_API_KEY",
  "isSecret": true,
  "isRequired": true
}
```

This ensures that MCP clients handle the credential with appropriate confidentiality measures.

Source: [server.json](https://github.com/quietnotion/barevalue-mcp/blob/main/server.json)

## Transport Security

### HTTPS Enforcement

All production API communication uses HTTPS to encrypt data in transit. The client explicitly uses the Node.js `https` module for secure connections:

```typescript
const isHttps = url.protocol === 'https:';
const httpModule = isHttps ? https : http;
```

For non-localhost URLs, a warning is emitted if a non-HTTPS connection is detected:

```typescript
const isHttps = url.protocol === 'https:';
if (!isHttps && url.hostname !== 'localhost' && url.hostname !== '127.0.0.1') {
  console.error('WARNING: Using non-HTTPS connection. API key may be transmitted insecurely.');
}
```

This warning mechanism alerts operators to potentially insecure configurations while allowing local development with HTTP.

Source: [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

### Request Headers

Every API request includes security-relevant headers:

| Header | Value | Purpose |
|--------|-------|---------|
| `Authorization` | `Bearer {apiKey}` | Authentication token |
| `Content-Type` | `application/json` | Ensures JSON parsing on server |
| `Accept` | `application/json` | Expects JSON response |
| `User-Agent` | `barevalue-mcp/1.0.0` | Server identification |

Source: [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

## Input Sanitization

The server implements input sanitization to protect against injection attacks and ensure safe data handling.

### Sanitization Functions

```typescript
function sanitizeString(str: string): string {
  return str.replace(/[\u0000-\u001F\u007F-\u009F]/g, (char) => 
    char.charCodeAt(0) < 0x20 || char.charCodeAt(0) > 0x7E 
      ? `\\x${char.charCodeAt(0).toString(16).padStart(2, '0')}`
      : char
  );
}

function sanitizeData(data: unknown): unknown {
  if (typeof data === 'string') {
    return sanitizeString(data);
  }
  if (Array.isArray(data)) {
    return data.map(sanitizeData);
  }
  if (data !== null && typeof data === 'object') {
    const result: Record<string, unknown> = {};
    for (const [key, value] of Object.entries(data)) {
      result[sanitizeString(key)] = sanitizeData(value);
    }
    return result;
  }
  return data;
}
```

The sanitization process:
1. Removes control characters from strings (bytes 0x00-0x1F and 0x7F-0x9F)
2. Recursively processes arrays and objects
3. Preserves printable ASCII characters and Unicode content

Source: [src/index.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

### Sanitization Application Points

Sanitization is applied in two primary locations:

1. **Tool Call Error Responses**: When a tool call fails, error messages are sanitized before being returned to clients
2. **Webhook Payloads**: Incoming webhook data is sanitized to prevent injection attacks

Source: [src/index.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

## Error Handling Security

### Information Leakage Prevention

The server is designed to avoid exposing sensitive information in error messages. Two specific safeguards are implemented:

**S3 Upload Errors**:
```typescript
// Security: Don't expose S3 error response data
reject(new Error(`S3 upload failed with status ${res.statusCode}`));
```

**API Response Parsing Failures**:
```typescript
// Security: Don't expose raw API response data in error messages
reject(new Error('Failed to parse API response'));
```

These measures ensure that internal system details, stack traces, or sensitive payload content are never exposed to end users or potential attackers.

Source: [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

### Error Response Structure

All tool call errors follow a standardized format:

```json
{
  "error": "tool_error",
  "message": "sanitized error message"
}
```

Source: [src/index.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/index.ts)

## Webhook Security

The Barevalue API provides webhook functionality for order status notifications. The MCP server includes full webhook management capabilities.

### HMAC-SHA256 Signature Verification

Incoming webhook requests are verified using HMAC-SHA256 signatures:

> Webhook signatures use HMAC-SHA256 for verification

This ensures that webhook payloads originate from the legitimate Barevalue API server and have not been tampered with in transit.

Source: [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

### Webhook Secret Rotation

The server supports webhook secret rotation to maintain security after potential compromises:

```
barevalue_webhook_rotate_secret webhook_id=1
```

Rotating secrets immediately invalidates the previous secret, ensuring that any previously leaked credentials stop working immediately.

Source: [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

### Webhook Management API

| Method | Endpoint | Purpose |
|--------|----------|---------|
| `GET` | `/webhooks` | List all webhooks |
| `POST` | `/webhooks` | Create a webhook |
| `GET` | `/webhooks/{id}` | Get specific webhook |
| `PATCH` | `/webhooks/{id}` | Update webhook configuration |
| `DELETE` | `/webhooks/{id}` | Delete a webhook |
| `POST` | `/webhooks/{id}/rotate-secret` | Rotate webhook secret |

Source: [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

## S3 Upload Security

### Presigned URL Expiration

File uploads use S3 presigned URLs that automatically expire:

> Presigned S3 URLs expire after 30 minutes

This temporal limitation reduces the risk of unauthorized access to uploaded files even if a presigned URL is intercepted.

Source: [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

### Content Type Validation

The client validates file content types based on extension:

```typescript
const types: Record<string, string> = {
  '.mp3': 'audio/mpeg',
  '.wav': 'audio/wav',
  '.m4a': 'audio/mp4',
  '.flac': 'audio/flac',
  '.aac': 'audio/aac',
  '.ogg': 'audio/ogg',
  '.wma': 'audio/x-ms-wma',
  '.aiff': 'audio/aiff',
  '.aif': 'audio/aiff',
};
return types[ext] || 'application/octet-stream';
```

Supported formats are limited to audio files, preventing upload of potentially malicious file types.

Source: [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

## Timeout Protection

The server implements timeout protection for all network operations:

```typescript
timeout: this.timeout
```

If a request exceeds the configured timeout, the connection is destroyed and an error is returned:

```typescript
req.on('timeout', () => {
  req.destroy();
  reject(new Error('API request timed out'));
});
```

This prevents resource exhaustion attacks that attempt to hold connections open indefinitely.

Source: [src/api-client.ts](https://github.com/quietnotion/barevalue-mcp/blob/main/src/api-client.ts)

## Rate Limiting

The API enforces rate limiting to prevent abuse:

- **10 requests per minute** per API key
- File uploads have a **5-minute timeout**
- Order processing typically completes in **10-30 minutes**

Source: [README.md](https://github.com/quietnotion/barevalue-mcp/blob/main/README.md)

## Security Architecture Diagram

```mermaid
graph TD
    subgraph "Client Environment"
        ENV[Environment Variables<br/>BAREVALUE_API_KEY<br/>BAREVALUE_API_URL]
    end

    subgraph "barevalue-mcp Server"
        SV[Server Startup]
        SV -->|Read| ENV
        
        subgraph "API Client"
            KVF[API Key Validation<br/>bv_sk_ prefix check]
            HTTPS_CHK[HTTPS Check<br/>Non-localhost warning]
            REQ[Request Builder<br/>Auth headers<br/>User-Agent]
            TO[Timeout Handler]
        end
        
        ENV --> KVF
        KVF --> HTTPS_CHK
        HTTPS_CHK --> REQ
        REQ --> TO
    end

    subgraph "Barevalue API"
        AUTH[Authentication]
        RATE[Rate Limiting<br/>10 req/min]
        WEBHOOK[Webhook HMAC-SHA256<br/>Signature Verification]
        S3[S3 Presigned URLs<br/>30 min expiration]
    end
    
    TO -->|HTTPS| AUTH
    AUTH --> RATE
    RATE -->|Success| WEBHOOK
    
    subgraph "File Upload Flow"
        PRE[Get Presigned URL]
        UPLOAD[Upload to S3]
        PRE --> UPLOAD
        UPLOAD -->|30 min expiry| S3
    end
```

## Best Practices

### For Users

1. **Never hardcode API keys** — Always use environment variables
2. **Use HTTPS in production** — The warning system alerts to insecure configurations
3. **Rotate webhook secrets** — Periodically rotate to maintain security
4. **Monitor rate limits** — Implement backoff logic for 429 responses
5. **Validate file formats** — Ensure uploaded files are legitimate audio content

### For Developers

1. **Preserve sanitization** — Don't remove input sanitization for convenience
2. **Maintain error secrecy** — Don't expose internal details in error messages
3. **Keep secrets as secrets** — Never log API keys or webhook secrets
4. **Update dependencies** — Keep the `@modelcontextprotocol/sdk` package current

## Summary

The barevalue-mcp implements defense-in-depth security measures across multiple layers:

| Layer | Protection Mechanism |
|-------|---------------------|
| Authentication | Bearer token with `bv_sk_` prefix validation |
| Transport | HTTPS enforcement with localhost exceptions |
| Input | Control character sanitization for all string inputs |
| Errors | No sensitive data exposure in error messages |
| Webhooks | HMAC-SHA256 signature verification |
| File Uploads | S3 presigned URLs with 30-minute expiration |
| Network | Request timeouts to prevent resource exhaustion |
| API | Rate limiting at 10 requests per minute |

---

---

## Doramagic Pitfall Log

Project: quietnotion/barevalue-mcp

Summary: Found 7 potential pitfall items; 0 are high/blocking. Highest priority: capability - 能力判断依赖假设.

## 1. capability · 能力判断依赖假设

- Severity: medium
- Evidence strength: source_linked
- Finding: README/documentation is current enough for a first validation pass.
- User impact: 假设不成立时，用户拿不到承诺的能力。
- Suggested check: 将假设转成下游验证清单。
- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。
- Evidence: capability.assumptions | mcp_registry:io.github.quietnotion/barevalue:1.0.3 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.quietnotion%2Fbarevalue/versions/1.0.3 | README/documentation is current enough for a first validation pass.

## 2. runtime · 运行可能依赖外部服务

- Severity: medium
- Evidence strength: source_linked
- Finding: 项目说明出现 external service/cloud/webhook/database 等运行依赖关键词。
- User impact: 本地安装成功不等于能力可用，外部服务不可用会阻断体验。
- Suggested check: 确认是否有离线 demo、mock 数据或可替代服务。
- Guardrail action: 外部服务依赖未明确时，不把本地安装成功等同于能力可用。
- Evidence: packet_text.keyword_scan | mcp_registry:io.github.quietnotion/barevalue:1.0.3 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.quietnotion%2Fbarevalue/versions/1.0.3 | matched external service / cloud / webhook / database keyword

## 3. maintenance · 维护活跃度未知

- Severity: medium
- Evidence strength: source_linked
- Finding: 未记录 last_activity_observed。
- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。
- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。
- Evidence: evidence.maintainer_signals | mcp_registry:io.github.quietnotion/barevalue:1.0.3 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.quietnotion%2Fbarevalue/versions/1.0.3 | last_activity_observed missing

## 4. security_permissions · 下游验证发现风险项

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 下游已经要求复核，不能在页面中弱化。
- Suggested check: 进入安全/权限治理复核队列。
- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。
- Evidence: downstream_validation.risk_items | mcp_registry:io.github.quietnotion/barevalue:1.0.3 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.quietnotion%2Fbarevalue/versions/1.0.3 | no_demo; severity=medium

## 5. security_permissions · 存在评分风险

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 风险会影响是否适合普通用户安装。
- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。
- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。
- Evidence: risks.scoring_risks | mcp_registry:io.github.quietnotion/barevalue:1.0.3 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.quietnotion%2Fbarevalue/versions/1.0.3 | no_demo; severity=medium

## 6. maintenance · issue/PR 响应质量未知

- Severity: low
- Evidence strength: source_linked
- Finding: issue_or_pr_quality=unknown。
- User impact: 用户无法判断遇到问题后是否有人维护。
- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。
- Guardrail action: issue/PR 响应未知时，必须提示维护风险。
- Evidence: evidence.maintainer_signals | mcp_registry:io.github.quietnotion/barevalue:1.0.3 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.quietnotion%2Fbarevalue/versions/1.0.3 | issue_or_pr_quality=unknown

## 7. maintenance · 发布节奏不明确

- Severity: low
- Evidence strength: source_linked
- Finding: release_recency=unknown。
- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。
- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。
- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。
- Evidence: evidence.maintainer_signals | mcp_registry:io.github.quietnotion/barevalue:1.0.3 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.quietnotion%2Fbarevalue/versions/1.0.3 | release_recency=unknown

<!-- canonical_name: quietnotion/barevalue-mcp; human_manual_source: deepwiki_human_wiki -->
