HED MCP Server

by hed-standard

Not rated
GitHub

About

An MCP server for Hierarchical Event Descriptors (HED) that automates sidecar creation and annotation for BIDS event files using LLMs.

Details

Author
hed-standard
Categories
Developer Tools, Other, Knowledge Base, AI

Setup

Install HED MCP Server in your MCP client (Claude Desktop, Cursor, Windsurf, and others).

Repository: https://github.com/hed-standard/hed-mcp

Follow the installation instructions in the repository README, then restart your MCP client.

A Model Context Protocol (MCP) server for validating HED (Hierarchical Event Descriptor) data. This server provides comprehensive HED validation tools through the standardized MCP interface, making HED validation accessible to any MCP-compatible client.

- A standardized vocabulary for describing experimental events
- A hierarchical system that allows for precise event annotation
- Widely used in BIDS (Brain Imaging Data Structure) datasets
- Essential for reproducible neuroscience research

- A standardized protocol for tool and resource sharing
- Enables AI assistants and applications to access external capabilities
- Provides a consistent interface across different implementations
- Facilitates integration between diverse software systems

- HED string validation: Validate individual HED tag strings against schema specifications
- TSV file validation: Validate entire BIDS TSV files containing HED annotations
- JSON sidecar validation: Parse and validate HED sidecar JSON files
- File system access: Read files from local filesystem paths
- Multi-schema support: Support for standard HED schemas and library schemas
- Definition processing: Handle HED definitions for enhanced validation
- Warning detection: Optional warning detection in addition to error reporting
- Schema caching: Intelligent caching system for optimal performance
- Multiple interfaces: MCP server (stdio/WebSocket) + HTTP REST API
- Browser compatibility: Full browser support with multiple integration options

- Understanding HED
-
Installation
-
Quick Start
-
Server Architecture
-
Available Tools
-
Usage Examples
-
Working with HED Data
-
Browser Usage
-
Configuration
-
Advanced Features
-
Performance Optimization
-
Integration Guide
-
Development
-
Troubleshooting
-
Testing
-
Contributing
-
License

HED uses a hierarchical tag structure where tags are organized from general to specific:

Event # General event type Event/Sensory-event # More specific Sensory-event # Same as Event/Sensory-event

The hierarchical structure is used for search generality -- allowing a search forEventto pick upEvent/Sensory-eventas well asSensory-event.

Note: All tags in the HED vocabulary are unique. It is recommended that you annotate using just the tag, not the full path.

- Path notation: Tags use forward slashes to indicate hierarchy
- Grouping: Parentheses group related tags:(Red, Large)
- Definitions: Custom definitions can be used for complex concepts
- Extension: Custom subtags can be added for specialization

You can create definitions to represent strings of tags that you frequently use:

(Definition/BlueSquare, ((Background-view, Black), ((Blue, Square), (Center-of, Computer-Screen))))

can appear anywhere a normal HED tag would. Tools can substitute the full annotation when needed.

HED schemas evolve over time. Use the latest version whenever possible:

- Standard HED:8.4.0- Basic vocabulary
- Library schemas:

- lang_1.1.0- Language-related tags
- score_2.1.0- EEG features based on SCORE standard

Before using the HED MCP Server, ensure you have:
- Node.js 22+: Download from
nodejs.org
- Basic understanding of HED: Familiarity with HED concepts is helpful
- MCP-compatible client: Such as the MCP Inspector or custom client

This creates the distribution files in thedist/directory.

npx @modelcontextprotocol/inspector node dist/server.js
HED MCP Server (src) ├── server.ts # Main MCP server (stdio/WebSocket modes) ├── tools/ # Validation functions │ ├── validateHedString.ts │ ├── validateHedTsv.ts │ ├── validateHedSidecar.ts │ └── getFileFromPath.ts ├── resources/ # Schema Information │ └── hedSchema.ts ├── utils/ # Utilities │ ├── definitionProcessor.ts │ ├── fileReader.ts │ ├── issueFormatter.ts │ ├── mcpToZod.ts │ └── schemaCache.ts # Schema caching system └── types/ # TypeScript definitions Examples (examples/) ├── definition-usage.ts # Example of HED definition processing ├── hed-demo.html # Interactive demo and integration guide ├── hed-validator-client.js # Modern browser client for HED validation ├── hed-validator.css # Styles for the browser interface ├── hed-validator.html # Full-featured browser validation interface ├── http-server.ts # HTTP REST API server example ├── mcp-client.js # Interactive MCP client example ├── README.md # README for the examples └── test-server.js # Automated server testing script

- Client request→ MCP server
- Schema loading→ Cache or load from network
- Data processing→ Parse and validate
- Issue formatting→ Standardize error/Warning format
- Response→ Return to client

The server implements intelligent caching:

- Schema caching: Avoids reloading schemas for repeated operations
- Definition caching: Reuses processed definitions
- Memory management: Automatic cleanup of unused cache entries

The fastest way to test the server is using the MCP Inspector:

npx @modelcontextprotocol/inspector node dist/server.js

This opens a web interface where you can interact with the server and test all available tools.

# Standard MCP server (stdio mode) npm start # WebSocket mode node dist/server.js --websocket --port=8080 # HTTP REST API server npm run start:http

- Open the MCP Inspectorin your browser
- Initialize the server- this happens automatically
- List available toolsto see what's available
- Try a simple validationwithvalidateHedString

Purpose: Validates individual HED tag strings

- Testing specific HED constructs
- Interactive validation during annotation
- Validating programmatically generated HED strings

- hedString(required): The HED string to validate
- hedVersion(required): Schema version (e.g., "8.4.0")
- checkForWarnings(optional): Include warnings in results
- definitions(optional): Array of definition strings

- Use specific schema versions in production
- Enable warnings during development
- Group related definitions together

Purpose: Validates TSV files containing HED annotations

- Validating BIDS event files
- Checking TSV files before publication
- Automated dataset validation

- filePath(required): Path to TSV file
- hedVersion(required): Schema version
- checkForWarnings(optional): Include warnings
- fileData(optional): Inline TSV data
- jsonData(optional): Sidecar data as JSON string
- definitions(optional): Definition strings

- UsefileDatafor small datasets to avoid file I/O
- Include sidecar data viajsonDatafor complete validation
- Process files in batches for large datasets

Purpose: Validates HED sidecar JSON files

- Validating BIDS sidecar files
- Checking JSON structure and HED content
- Converting between sidecar formats

- filePath(required): Path to JSON sidecar file
- hedVersion(required): Schema version
- checkForWarnings(optional): Include warnings
- fileData(optional): Inline JSON data

- Validate sidecar files before TSV files
- Use parsed output for debugging sidecar structure
- Check both structure and HED content validity

Purpose: Retrieves files from the local filesystem

- Reading configuration files
- Accessing data files for validation
- File system operations

- filePath(required): Absolute path to the file

- Use absolute file paths
- Check file permissions and existence
- Handle file encoding properly (UTF-8 recommended)

{ "method": "tools/call", "params": { "name": "validateHedString", "arguments": { "hedString": "Event/Sensory-event, Red, Blue, (Green, Large)", "hedVersion": "8.4.0", "checkForWarnings": true } } }
{ "method": "tools/call", "params": { "name": "validateHedTsv", "arguments": { "filePath": "/tests/data/sub-002_ses-1_task-FacePerception_run-1_events.tsv", "hedVersion": "8.4.0", "checkForWarnings": true, "definitions": [ "(Definition/Fixation, (Sensory-event, Visual-presentation, (Image, Cross))", "(Definition/ButtonPress, (Press, Mouse-button))" ] } } }
{ "method": "tools/call", "params": { "name": "validateHedSidecar", "arguments": { "filePath": "/tests/data/task-FacePerception_events.json", "hedVersion": "8.4.0", "checkForWarnings": false } } }
{ "method": "tools/call", "params": { "name": "getFileFromPath", "arguments": { "filePath": "/path/to/data/events.tsv" } } }

- Schema Selection: Choose appropriate HED schema version
- Definition Setup: Prepare any custom definitions
- Data Validation: Run appropriate validation tool
- Issue Resolution: Address errors and warnings
- Quality Assurance: Final validation with warnings enabled

// 1. First validate sidecar files { "name": "validateHedSidecar", "arguments": { "filePath": "/data/task-rest_events.json", "hedVersion": "8.4.0", "checkForWarnings": true } } // 2. Then validate TSV files with sidecar data { "name": "validateHedTsv", "arguments": { "filePath": "/data/sub-01_task-rest_events.tsv", "hedVersion": "8.4.0", "jsonData": "{...sidecar content...}", "checkForWarnings": true } }
// Test individual HED strings during annotation { "name": "validateHedString", "arguments": { "hedString": "Event/Sensory-event, (Red, Large)", "hedVersion": "8.4.0", "checkForWarnings": true } }
// Test definitions before using in datasets { "name": "validateHedString", "arguments": { "hedString": "Def/MyStimulus, Blue", "hedVersion": "8.4.0", "definitions": [ "(Definition/MyStimulus, (Event/Sensory-event, (Onset)))" ], "checkForWarnings": true } }

- Check spelling and capitalization
- Verify tag exists in specified schema version
- Consider using extension tags if appropriate

DEFINITION_INVALID: Malformed definition

- Ensure proper parentheses around definition content
- Check that definition name follows conventions
- Verify definition content is valid HED

SCHEMA_LOAD_FAILED: Invalid schema version

- Verify schema version exists
- Check network connectivity for schema download
- Use stable, released schema versions

FILE_READ_ERROR: Cannot read specified file

- Verify file path and permissions
- Check file exists and is readable
- Consider using inline data for virtual files

- Consider using more specific standard tags
- Acceptable for novel experimental paradigms
- Document extensions for reproducibility

- Non-critical definition problems
- May indicate style or convention issues
- Review definition structure and content
- Specificity: Use most specific appropriate tags
- Consistency: Apply same annotation patterns throughout dataset
- Completeness: Annotate all relevant aspects of events
- Accuracy: Ensure annotations match actual experimental events

- All files validate without errors
- Warnings reviewed and addressed where appropriate
- Definitions properly documented
- Schema version appropriate for dataset
- Annotations consistent across similar events

The HED MCP server can be used in browsers through several approaches. All browser files are located in theexamples/directory.

Openexamples/hed-validator.htmlfor a full-featured web interface:

- Multiple validation modes: String, TSV, and Sidecar validation
- Modern UI: Clean, responsive design with professional styling
- Real-time feedback: Instant validation results with detailed error reporting
- Multiple HED versions: Support for different schema versions and libraries

# Serve the examples locally npx serve examples/ # Or open directly in browser open examples/hed-validator.html

Option 2: Interactive Demo & Integration Guide

- Live examples: Pre-configured validation scenarios
- Integration guide: Complete API documentation and code examples
- Developer tools: Quick validation form for testing

Include the modern browser client in your web application:

<link rel="stylesheet" href="examples/hed-validator.css"> <script src="examples/hed-validator-client.js"></script> <script> // Create validator client (auto-detects server availability) const validator = new HEDValidatorClient(); // Validate HED string const result = await validator.validateString('Event/Sensory-event, Red'); // Or create a pre-built validation form HEDValidatorClient.createValidationForm('my-container'); </script>

For complete server-based validation, run the HTTP API server:

npm run build node dist/examples/http-server.js

The browser client automatically detects and uses the server athttp://localhost:3000/api/hed/.

Quick Start: Openexamples/hed-validator.htmlto immediately start validating HED data in your browser!

<!DOCTYPE html> <html> <head> <title>HED Validator</title> </head> <body> <textarea id="hedInput" placeholder="Enter HED string..."></textarea> <button onclick="validateHED()">Validate</button> <div id="results"></div> <script> async function validateHED() { const hedString = document.getElementById('hedInput').value; try { const response = await fetch('/api/validate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ hedString, hedVersion: '8.4.0', checkForWarnings: true }) }); const result = await response.json(); displayResults(result); } catch (error) { console.error('Validation failed:', error); } } function displayResults(result) { const resultsDiv = document.getElementById('results'); if (result.errors.length === 0) { resultsDiv.innerHTML = '<p style="color: green;">Valid HED string!</p>'; } else { resultsDiv.innerHTML = '<p style="color: red;">Validation errors:</p>'; result.errors.forEach(error => { resultsDiv.innerHTML += <p>• ${error.message}</p>; }); } if (result.warnings.length > 0) { resultsDiv.innerHTML += '<p style="color: orange;">Warnings:</p>'; result.warnings.forEach(warning => { resultsDiv.innerHTML += <p>• ${warning.message}</p>; }); } } </script> </body> </html>
{ "servers": { "hed-mcp": { "command": "node", "args": ["dist/server.js"], "cwd": "/path/to/hed-mcp-typescript" } } }

Run the server in WebSocket mode for browser-based MCP clients:

node dist/server.js --websocket --port=8080
No reviews yet — be the first

Sign in to leave a review

Use Google, GitHub, or an email account so ratings stay tied to real people.

Email sign in

No reviews posted yet.