npm package: @fluree/fluree-mcp-server
Description: TypeScript MCP server for Fluree database access
Author: Fluree
Latest version: 1.3.3

# Fluree MCP Server (TypeScript)

A TypeScript/Node.js implementation of the Model Context Protocol (MCP) server for Fluree database access.

## Features

- **SPARQL Query Execution**: Execute SPARQL queries with automatic FROM clause injection
- **Data Agent Support**: Query multiple datasets through Fluree data agents
- **Data Model Caching**: Efficient caching of schema information with TTL and LRU eviction
- **Flexible Data Model Source**: Optional separate dataset for data model vs SPARQL queries when model is not in main data dataset
- **Session Management**: Support for Fluree API keys and Nexus session tokens
- **Error Handling**: Intelligent error classification for LLM learning
- **Multiple Prompts**: Built-in prompts for query generation, error handling, and schema summarization

## Installation

### From NPM

```bash
npm install @fluree/fluree-mcp-server
# or
yarn add @fluree/fluree-mcp-server
```

### From Source

```bash
yarn install
yarn build
```

## Usage

### Command Line

```bash
# Development mode
yarn dev

# Production mode
yarn start

# Watch mode for development
yarn watch

# CLI Arguments
yarn dev --help                                    # Show all available options
yarn dev --dataset "user/dataset"                  # Single dataset mode
yarn dev --data-agent "agent-name"                 # Data agent mode (multiple datasets)
yarn dev --data-model-dataset "company/schema"     # Separate dataset for data model
yarn dev --fluree-api-key "handle=your_api_key"    # API key authentication
yarn dev --nexus-session-token "your_token"        # Session token authentication
yarn dev --transport stdio                         # Override transport type
yarn dev --port 8080                               # Custom port
yarn dev --dataset-policy "ds1=policy1,policy2"   # Dataset policies

# Note: --dataset and --data-agent are mutually exclusive

# Environment Variables
LOG_LEVEL=debug yarn dev                           # Enable debug logging
MCP_TRANSPORT=sse yarn dev                         # Set transport via environment
```

### Claude Desktop Integration

Add the following to your Claude Desktop configuration:

```json
{
  "mcpServers": {
    "fluree": {
      "command": "npx",
      "args": ["@fluree/fluree-mcp-server"],
      "env": {
        "FLUREE_BASE_URL": "https://app.949824632714.flur.ee",
        "FLUREE_DATASET": "your/dataset",
        "FLUREE_API_KEY": "your-api-key",
        "FLUREE_API_HANDLE": "your-handle"
      }
    }
  }
}
```

Or if you prefer to install globally:

```bash
npm install -g @fluree/fluree-mcp-server
```

Then use:

```json
{
  "mcpServers": {
    "fluree": {
      "command": "fluree-mcp-server",
      "env": {
        "FLUREE_BASE_URL": "https://app.949824632714.flur.ee",
        "FLUREE_DATASET": "your/dataset",
        "FLUREE_API_KEY": "your-api-key",
        "FLUREE_API_HANDLE": "your-handle"
      }
    }
  }
}
```

## Configuration

### Dataset vs Data Agent Mode

The server can operate in one of two modes:

1. **Dataset Mode** - Query a single specific dataset
   - Use `--dataset` CLI arg or `FLUREE_DATASET` env var
   - Example: `--dataset "user/my-dataset"`
2. **Data Agent Mode** - Query multiple datasets through a data agent
   - Use `--data-agent` CLI arg or `FLUREE_DATA_AGENT` env var
   - Example: `--data-agent "my-agent"`
   - The data agent handles dataset selection internally

**Important:** These modes are mutually exclusive. You cannot specify both a dataset and a data agent.

### Environment Variables

The server supports configuration via environment variables or a `.env` file:

**Core Configuration:**

- `MCP_TRANSPORT`: Transport type (stdio, sse, http) - default: sse
- `FLUREE_BASE_URL`: Fluree instance URL
- `BIND_ADDRESS`: Server bind address - default: 127.0.0.1
- `SERVER_PORT`: Server port - default: 3456
- `LOG_LEVEL`: Log level (error, warn, info, debug) - default: info

**Session Configuration:**

- `FLUREE_DATASET`: Single dataset to use (conflicts with FLUREE_DATA_AGENT)
- `FLUREE_DATA_AGENT`: Data agent to use for accessing multiple datasets (conflicts with FLUREE_DATASET)
- `DATA_MODEL_DATASET`: Optional dataset to use for fetching the data model (works with either FLUREE_DATASET or FLUREE_DATA_AGENT)
- `FLUREE_API_KEY`: Default Fluree API key
- `FLUREE_API_HANDLE`: Default Fluree API handle
- `NEXUS_SESSION_TOKEN`: Nexus session token (alternative to API key)
- `POLICY_GROUPS`: JSON string of dataset policies

**Legacy (Deprecated):**

- `STARTUP_DATASETS`: Legacy comma-separated datasets (deprecated - use FLUREE_DATASET instead)

**Performance Configuration:**

- `RATE_LIMIT_PER_MINUTE`: Rate limiting - default: 100
- `CIRCUIT_BREAKER_FAILURE_THRESHOLD`: Circuit breaker failure threshold - default: 5
- `CIRCUIT_BREAKER_TIMEOUT_SECS`: Circuit breaker timeout - default: 60
- `CIRCUIT_BREAKER_HALF_OPEN_MAX_CALLS`: Half-open max calls - default: 3
- `HTTP_REQUEST_TIMEOUT_MS`: HTTP request timeout - default: 30000
- `HTTP_CONNECTION_TIMEOUT_SECS`: HTTP connection timeout - default: 10

**Fallback Configuration:**

- `DEFAULT_FLUREE_API_KEY`: Fallback API key
- `DEFAULT_FLUREE_HANDLE`: Fallback API handle

### Using .env Files

Create a `.env` file in the project root (copy from `.env.example`):

```bash
# Copy the example file
cp .env.example .env

# Edit with your configuration
nano .env
```

Example `.env` file:

```env
MCP_TRANSPORT=stdio
FLUREE_BASE_URL=https://app.949824632714.flur.ee
FLUREE_QUERY_URL=https://api.fluree.cloud
STARTUP_DATASETS=your/dataset
DATA_MODEL_DATASET=company/shared-schema
FLUREE_API_KEY=your-api-key
FLUREE_API_HANDLE=your-handle
```

## Available Tools

### `get_data_model`

Retrieves and caches the data model schema from configured Fluree datasets.

### `sparql_query`

Executes SPARQL queries against session datasets with automatic FROM clause injection.

Parameters:

- `query` (required): The SPARQL query to execute

## Available Resources

### `fluree://session`

Current session information including datasets, policies, and cache status.

### `fluree://data-model`

The currently cached data model schema if available.

## Available Prompts

### `sparql_query_helper`

Generate SPARQL queries from natural language descriptions using the data model.

### `data_model_summarizer`

Create user-friendly summaries of complex data models.

### `sparql_error_handler`

Analyze SPARQL errors and provide corrected queries.

## Data Model Configuration

The server supports flexible data model sourcing:

### Default Behavior

By default, the data model is fetched from the same datasets used for SPARQL queries.

### Separate Data Model Dataset

You can optionally specify a different dataset for fetching the data model:

```bash
# CLI
yarn dev --dataset "company/customer-data" --data-model-dataset "company/shared-schema"

# Environment Variable
STARTUP_DATASETS=company/customer-data
DATA_MODEL_DATASET=company/shared-schema
```

This is useful for:

- **Shared Schemas**: Use a common schema across multiple data datasets
- **Development**: Reference production schema while querying test data
- **Performance**: Cache stable schema from a dedicated source

## Architecture

The server is built with:

- **@modelcontextprotocol/sdk**: Official MCP SDK for TypeScript
- **TypeScript**: Type-safe development
- **Node.js**: Runtime environment
- **Fetch API**: HTTP client for Fluree API calls

## Error Handling

The server distinguishes between:

- **Business Logic Errors** (400, 404): Returned as successful tool calls with structured error information
- **Infrastructure Errors** (5xx, network): Returned as tool execution failures

This approach helps LLMs learn from query mistakes while properly handling system failures.

## Development

```bash
# Install dependencies
yarn install

# Start development server
yarn dev

# Build for production
yarn build

# Run built version
yarn start
```

## License

MIT