mcp-json
Version:
MCP server for JSON file operations - read, analyze, search, find, relate, validate, and write JSON files
373 lines (310 loc) • 8.1 kB
Markdown
# MCP JSON Server
A Model Context Protocol (MCP) server for comprehensive JSON file operations. This server provides tools for reading, analyzing, searching, transforming, validating, and manipulating JSON files with advanced features like JSONPath queries and schema validation.
## Features
- **File Discovery**: Find JSON files with glob patterns
- **Reading & Parsing**: Read and parse JSON files with error handling
- **Analysis**: Deep analysis of JSON structure, types, and metadata
- **Search**: Content search with JSONPath support
- **Transformation**: Various JSON transformation operations
- **Validation**: JSON syntax and schema validation using AJV
- **Querying**: JSONPath expressions for complex data extraction
- **Relationships**: Analyze relationships between JSON files
- **Merging**: Multiple merge strategies for combining JSON files
## Installation
```bash
npm install
npm run build
```
## Available Tools
### 1. `find_json_files`
Find JSON files in directories with pattern matching.
**Parameters:**
- `directory` (optional): Directory to search (defaults to current directory)
- `pattern` (optional): Glob pattern (defaults to `**/*.json`)
**Example:**
```json
{
"name": "find_json_files",
"arguments": {
"directory": "./data",
"pattern": "**/*.json"
}
}
```
### 2. `read_json_file`
Read and parse a JSON file.
**Parameters:**
- `filePath` (required): Path to the JSON file
**Example:**
```json
{
"name": "read_json_file",
"arguments": {
"filePath": "./example/users.json"
}
}
```
### 3. `analyze_json_file`
Analyze JSON file structure and provide detailed metadata.
**Parameters:**
- `filePath` (required): Path to the JSON file
**Example:**
```json
{
"name": "analyze_json_file",
"arguments": {
"filePath": "./example/products.json"
}
}
```
### 4. `search_json_content`
Search for content within JSON files with optional JSONPath filtering.
**Parameters:**
- `searchTerm` (required): Term to search for
- `directory` (optional): Directory to search
- `jsonPath` (optional): JSONPath expression to limit search scope
**Example:**
```json
{
"name": "search_json_content",
"arguments": {
"searchTerm": "John",
"directory": "./example",
"jsonPath": "$..name"
}
}
```
### 5. `write_json_file`
Write JavaScript objects to JSON files.
**Parameters:**
- `filePath` (required): Output file path
- `data` (required): JavaScript object to write
- `indent` (optional): Indentation spaces (default: 2)
**Example:**
```json
{
"name": "write_json_file",
"arguments": {
"filePath": "./output/new-data.json",
"data": {
"name": "Test User",
"age": 25
},
"indent": 4
}
}
```
### 6. `transform_json`
Transform JSON files using various operations.
**Parameters:**
- `filePath` (required): Input file path
- `outputPath` (required): Output file path
- `operation` (required): One of: `filter_keys`, `rename_keys`, `add_properties`, `remove_properties`, `flatten`, `unflatten`
- `parameters` (optional): Operation-specific parameters
**Examples:**
Filter keys:
```json
{
"name": "transform_json",
"arguments": {
"filePath": "./example/users.json",
"outputPath": "./output/filtered-users.json",
"operation": "filter_keys",
"parameters": {
"keysToKeep": ["name", "email"]
}
}
}
```
Rename keys:
```json
{
"name": "transform_json",
"arguments": {
"filePath": "./example/users.json",
"outputPath": "./output/renamed-users.json",
"operation": "rename_keys",
"parameters": {
"keyMapping": {
"name": "fullName",
"email": "emailAddress"
}
}
}
}
```
Flatten object:
```json
{
"name": "transform_json",
"arguments": {
"filePath": "./example/users.json",
"outputPath": "./output/flat-users.json",
"operation": "flatten",
"parameters": {
"separator": "."
}
}
}
```
### 7. `validate_json`
Validate JSON syntax and optionally against a JSON Schema.
**Parameters:**
- `filePath` (required): Path to JSON file to validate
- `schema` (optional): JSON Schema for validation
**Example:**
```json
{
"name": "validate_json",
"arguments": {
"filePath": "./example/users.json",
"schema": {
"type": "array",
"items": {
"type": "object",
"required": ["id", "name", "email"],
"properties": {
"id": { "type": "number" },
"name": { "type": "string" },
"email": { "type": "string", "format": "email" }
}
}
}
}
}
```
### 8. `query_json`
Execute JSONPath expressions to extract specific data.
**Parameters:**
- `filePath` (required): Path to JSON file
- `jsonPath` (required): JSONPath expression
**Examples:**
```json
{
"name": "query_json",
"arguments": {
"filePath": "./example/users.json",
"jsonPath": "$[*].name"
}
}
```
```json
{
"name": "query_json",
"arguments": {
"filePath": "./example/products.json",
"jsonPath": "$.products[?(@.inStock==true)].name"
}
}
```
### 9. `relate_json_files`
Find relationships between JSON files.
**Parameters:**
- `directory` (optional): Directory to analyze
- `relationType` (required): One of: `common_keys`, `shared_values`, `similar_structure`, `reference_links`
**Example:**
```json
{
"name": "relate_json_files",
"arguments": {
"directory": "./example",
"relationType": "common_keys"
}
}
```
### 10. `merge_json_files`
Merge multiple JSON files using different strategies.
**Parameters:**
- `filePaths` (required): Array of file paths to merge
- `outputPath` (required): Output file path
- `strategy` (required): One of: `merge`, `concat`, `deep_merge`
**Examples:**
Simple merge (object properties):
```json
{
"name": "merge_json_files",
"arguments": {
"filePaths": ["./file1.json", "./file2.json"],
"outputPath": "./merged.json",
"strategy": "merge"
}
}
```
Deep merge (nested objects):
```json
{
"name": "merge_json_files",
"arguments": {
"filePaths": ["./config1.json", "./config2.json"],
"outputPath": "./final-config.json",
"strategy": "deep_merge"
}
}
```
Array concatenation:
```json
{
"name": "merge_json_files",
"arguments": {
"filePaths": ["./users1.json", "./users2.json"],
"outputPath": "./all-users.json",
"strategy": "concat"
}
}
```
## Usage with MCP Clients
Configure in your MCP client:
```json
{
"mcpServers": {
"mcp-json": {
"command": "node",
"args": ["./dist/index.js"],
"env": {}
}
}
}
```
## JSONPath Examples
JSONPath is a powerful query language for JSON. Here are some useful patterns:
- `$.store.book[*]` - All books in store
- `$..author` - All author values (recursive)
- `$.store.book[?(@.price < 10)]` - Books cheaper than 10
- `$.store.book[-1:]` - Last book
- `$.store.book[0,1]` - First two books
- `$..*` - All values in the object
## Dependencies
- **/sdk**: MCP SDK for server implementation
- **ajv**: JSON Schema validation with excellent performance
- **ajv-formats**: Additional formats for AJV (email, date, etc.)
- **jsonpath**: JSONPath query support
- **lodash**: Utility functions for deep merging and object manipulation
- **glob**: File pattern matching
- **fs-extra**: Enhanced file system operations
## Error Handling
The server provides comprehensive error handling:
- **Syntax Errors**: Invalid JSON files are caught and reported
- **Schema Validation**: Detailed validation errors with AJV
- **File System**: Proper handling of missing files and permissions
- **JSONPath**: Invalid expressions are caught gracefully
- **Type Safety**: TypeScript ensures type safety throughout
## Testing
Run the test suite:
```bash
npm test
```
## License
MIT License
## Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request
## Roadmap
- [ ] JSON Patch operations (RFC 6902)
- [ ] JSON Pointer support (RFC 6901)
- [ ] Stream processing for large JSON files
- [ ] JSON-LD support
- [ ] Custom validation rules
- [ ] Performance benchmarking tools