Initial commit

This commit is contained in:
Felix Zösch
2025-12-11 20:30:12 +01:00
commit 3e23474476
21 changed files with 5327 additions and 0 deletions

465
README.md Normal file
View File

@@ -0,0 +1,465 @@
# InfluxDB MCP Server
A Model Context Protocol (MCP) server that provides seamless integration with InfluxDB v2. This server enables AI assistants like Claude to interact with your InfluxDB time-series database through a standardized protocol.
## Features
- **Health Monitoring**: Check InfluxDB server status and health
- **Bucket Management**: List, create, and delete buckets
- **Data Operations**: Query and write time-series data
- **Schema Discovery**: Explore measurements, tags, and fields
- **Organization Management**: View and manage organizations
- **Task & Dashboard Access**: List scheduled tasks and dashboards
- **Flux Query Support**: Execute powerful Flux queries for data analysis
## Prerequisites
- Node.js 18.0.0 or higher
- InfluxDB v2.x instance (local or remote)
- InfluxDB authentication token with appropriate permissions
## Installation
1. Clone or download this repository:
```bash
git clone <repository-url>
cd influxdb-mcp-server
```
2. Install dependencies:
```bash
npm install
```
3. Build the TypeScript code:
```bash
npm run build
```
### Docker Installation (Alternative)
You can also run the MCP server in a Docker container:
1. **Create environment file:**
```bash
cp .env.example .env
# Edit .env with your InfluxDB details
```
2. **Build and run with Docker Compose:**
```bash
docker-compose up -d
```
3. **View logs:**
```bash
docker-compose logs -f
```
For detailed Docker setup including Docker Desktop MCP integration, see [DOCKER.md](DOCKER.md).
## Configuration
Create a `.env` file in the project root with your InfluxDB credentials:
```bash
cp .env.example .env
```
Edit `.env` and configure the following variables:
```env
INFLUX_URL=http://localhost:8086
INFLUX_TOKEN=your_influxdb_token_here
INFLUX_ORG=your_organization_name
```
### Getting Your InfluxDB Token
1. Open the InfluxDB UI (typically http://localhost:8086)
2. Navigate to **Data** → **API Tokens**
3. Click **Generate API Token**
4. Choose **All Access Token** or create a custom token with specific permissions
5. Copy the token and add it to your `.env` file
## Usage with Claude Desktop
Add this server to your Claude Desktop configuration:
### macOS/Linux
Edit `~/Library/Application Support/Claude/claude_desktop_config.json`:
```json
{
"mcpServers": {
"influxdb": {
"command": "node",
"args": ["/absolute/path/to/influxdb-mcp-server/dist/index.js"],
"env": {
"INFLUX_URL": "http://localhost:8086",
"INFLUX_TOKEN": "your_influxdb_token_here",
"INFLUX_ORG": "your_organization_name"
}
}
}
}
```
### Windows
Edit `%APPDATA%\Claude\claude_desktop_config.json` with the same structure.
### Docker Configuration
To use the Docker version with Claude Desktop:
```json
{
"mcpServers": {
"influxdb": {
"command": "docker",
"args": [
"run",
"--rm",
"-i",
"--network=host",
"-e", "INFLUX_URL=http://localhost:8086",
"-e", "INFLUX_TOKEN=your_influxdb_token",
"-e", "INFLUX_ORG=your_organization",
"influxdb-mcp-server:latest"
]
}
}
}
```
After adding the configuration, restart Claude Desktop.
## MCP Resources
The server exposes the following read-only resources:
| URI | Description |
|-----|-------------|
| `influx://health` | Current health status of the InfluxDB server |
| `influx://buckets` | List of all buckets in the organization |
| `influx://buckets/{id}` | Details of a specific bucket |
| `influx://orgs` | List of all organizations |
| `influx://tasks` | List of all scheduled tasks |
| `influx://dashboards` | List of all dashboards |
## MCP Tools
The server provides the following tools for interacting with InfluxDB:
### query_flux
Execute a Flux query and return results.
**Parameters:**
- `query` (string, required): The Flux query to execute
- `org` (string, optional): Organization name
**Example:**
```flux
from(bucket: "my-bucket")
|> range(start: -1h)
|> filter(fn: (r) => r._measurement == "temperature")
|> mean()
```
### write_data
Write time-series data in line protocol format.
**Parameters:**
- `bucket` (string, required): Target bucket name
- `org` (string, required): Organization name
- `data` (string, required): Data in line protocol format
- `precision` (string, optional): Timestamp precision (ns, us, ms, s)
**Example:**
```
temperature,location=office,sensor=1 value=22.5 1672531200000000000
temperature,location=warehouse,sensor=2 value=18.3 1672531200000000000
```
### create_bucket
Create a new bucket with optional retention policy.
**Parameters:**
- `name` (string, required): Bucket name
- `org_id` (string, required): Organization ID
- `retention_seconds` (number, optional): Retention period (0 = infinite)
- `description` (string, optional): Bucket description
### delete_bucket
Delete a bucket by ID. **Warning:** This is irreversible.
**Parameters:**
- `bucket_id` (string, required): ID of the bucket to delete
### list_measurements
List all measurements (metric names) in a bucket.
**Parameters:**
- `bucket` (string, required): Bucket name
- `start` (string, optional): Start time (default: -30d)
- `stop` (string, optional): Stop time
**Time formats:**
- Relative: `-1h`, `-7d`, `-30d`
- Absolute: `2024-01-01T00:00:00Z`
### get_bucket_schema
Get schema information including measurements, tags, and fields.
**Parameters:**
- `bucket` (string, required): Bucket name
- `start` (string, optional): Start time for analysis (default: -7d)
- `stop` (string, optional): Stop time
## Example Interactions
Here are some example interactions you can have with Claude using this MCP server:
### Query Recent Data
> "Show me the average CPU usage from the 'system-metrics' bucket over the last hour"
Claude will use the `query_flux` tool to execute an appropriate Flux query.
### Write Sensor Data
> "Write temperature readings: office sensor at 22.5°C and warehouse sensor at 18.3°C to the 'sensors' bucket"
Claude will format the data in line protocol and use the `write_data` tool.
### Explore Schema
> "What measurements and fields are available in the 'application-logs' bucket?"
Claude will use the `get_bucket_schema` tool to discover the data structure.
### Create New Bucket
> "Create a new bucket called 'test-metrics' with a 30-day retention policy"
Claude will first get the organization ID from resources, then use the `create_bucket` tool.
### Health Check
> "Is my InfluxDB server running properly?"
Claude will read the `influx://health` resource to check server status.
## Architecture
```
influxdb-mcp-server/
├── src/
│ ├── index.ts # Main MCP server implementation
│ ├── influx-client.ts # InfluxDB REST API client
│ └── types.ts # TypeScript type definitions
├── dist/ # Compiled JavaScript (generated)
├── package.json # Dependencies and scripts
├── tsconfig.json # TypeScript configuration
├── .env.example # Environment variable template
└── README.md # This file
```
### Technology Stack
- **MCP SDK**: `@modelcontextprotocol/sdk` v1.0.4
- **HTTP Client**: `axios` for REST API communication
- **Validation**: `zod` for environment variable validation
- **Runtime**: Node.js with ES modules
- **Language**: TypeScript targeting ES2022
## API Coverage
This MCP server implements the following InfluxDB v2 API endpoints:
| Endpoint | Method | Status |
|----------|--------|--------|
| `/health` | GET | ✅ Implemented |
| `/api/v2/query` | POST | ✅ Implemented |
| `/api/v2/write` | POST | ✅ Implemented |
| `/api/v2/buckets` | GET | ✅ Implemented |
| `/api/v2/buckets` | POST | ✅ Implemented |
| `/api/v2/buckets/{id}` | GET | ✅ Implemented |
| `/api/v2/buckets/{id}` | DELETE | ✅ Implemented |
| `/api/v2/orgs` | GET | ✅ Implemented |
| `/api/v2/tasks` | GET | ✅ Implemented |
| `/api/v2/dashboards` | GET | ✅ Implemented |
Additional functionality through Flux schema functions:
- `schema.measurements()` - List measurements
- `schema.measurementTagKeys()` - List tag keys
- `schema.measurementFieldKeys()` - List field keys
## Development
### Build
```bash
npm run build
```
### Watch Mode
```bash
npm run watch
```
### Run Directly
```bash
npm start
```
### Debug Mode
For debugging, you can run the server with additional logging:
```bash
node dist/index.js
```
The server logs to stderr, so it won't interfere with the MCP protocol communication on stdout.
## Troubleshooting
### Connection Issues
**Problem:** "No response from InfluxDB server"
**Solutions:**
- Verify `INFLUX_URL` is correct and InfluxDB is running
- Check network connectivity: `curl http://localhost:8086/health`
- Ensure no firewall is blocking the connection
### Authentication Errors
**Problem:** "InfluxDB API error (401): unauthorized"
**Solutions:**
- Verify your `INFLUX_TOKEN` is correct
- Check token permissions in InfluxDB UI
- Ensure token hasn't expired
### Query Failures
**Problem:** Flux query returns an error
**Solutions:**
- Validate Flux syntax using InfluxDB UI Query Builder
- Check bucket name and organization are correct
- Ensure time range contains data
- Verify measurement and field names exist
### Resource Not Found
**Problem:** "Unknown resource URI"
**Solutions:**
- Check the URI format matches documented patterns
- For bucket-specific resources, verify the bucket ID exists
- Use `influx://buckets` to list available bucket IDs
### Tool Execution Errors
**Problem:** "Tool execution failed"
**Solutions:**
- Verify all required parameters are provided
- Check parameter types match the schema
- For write operations, validate line protocol format
- For bucket creation, ensure organization ID (not name) is used
## Security Considerations
1. **Token Storage**: Never commit `.env` files or tokens to version control
2. **Token Permissions**: Use least-privilege tokens with only necessary permissions
3. **Network Security**: Use HTTPS for remote InfluxDB instances
4. **Input Validation**: The server validates all inputs using Zod schemas
5. **Error Messages**: Sensitive information is not exposed in error messages
## Line Protocol Format
When writing data, use the InfluxDB line protocol format:
```
<measurement>[,<tag_key>=<tag_value>[,<tag_key>=<tag_value>]] <field_key>=<field_value>[,<field_key>=<field_value>] [<timestamp>]
```
**Examples:**
```
# Simple measurement
temperature value=22.5
# With tags
temperature,location=office,sensor=1 value=22.5
# Multiple fields
weather,location=garden temperature=22.5,humidity=65.2
# With timestamp (nanoseconds)
cpu,host=server1 usage=45.2 1672531200000000000
# Multiple lines (batch write)
cpu,host=server1 usage=45.2 1672531200000000000
cpu,host=server2 usage=38.7 1672531200000000000
memory,host=server1 used=8589934592 1672531200000000000
```
## Flux Query Examples
### Basic Query
```flux
from(bucket: "my-bucket")
|> range(start: -1h)
|> filter(fn: (r) => r._measurement == "cpu")
```
### Aggregation
```flux
from(bucket: "my-bucket")
|> range(start: -24h)
|> filter(fn: (r) => r._measurement == "temperature")
|> aggregateWindow(every: 1h, fn: mean)
```
### Multiple Filters
```flux
from(bucket: "my-bucket")
|> range(start: -1h)
|> filter(fn: (r) => r._measurement == "cpu" and r.host == "server1")
|> filter(fn: (r) => r._field == "usage")
```
### Join Data
```flux
cpu = from(bucket: "my-bucket")
|> range(start: -1h)
|> filter(fn: (r) => r._measurement == "cpu")
memory = from(bucket: "my-bucket")
|> range(start: -1h)
|> filter(fn: (r) => r._measurement == "memory")
join(tables: {cpu: cpu, memory: memory}, on: ["_time", "host"])
```
## Contributing
Contributions are welcome! Please feel free to submit issues or pull requests.
## License
MIT License - See LICENSE file for details
## Support
For issues and questions:
- InfluxDB Documentation: https://docs.influxdata.com/influxdb/v2/
- Flux Language Guide: https://docs.influxdata.com/flux/v0/
- MCP Documentation: https://modelcontextprotocol.io/
## Acknowledgments
Built with the Model Context Protocol SDK and inspired by the ha-mcp-server reference implementation.