# Directory Structure ``` ├── .gitignore ├── eslint.config.mjs ├── LICENSE ├── nodemon.json ├── package.json ├── README.md ├── src │ ├── common │ │ ├── constants.ts │ │ ├── tools.ts │ │ ├── types.ts │ │ └── utils.ts │ └── index.ts └── tsconfig.json ``` # Files -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- ``` node_modules build .env .env.local .env.development .env.production .env.test .env.test.local .env.production.local yarn.lock package-lock.json ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- ```markdown # Custom Context MCP Server This Model Context Protocol (MCP) server provides tools for structuring and extracting data from text according to JSON templates. ## Features ### Text-to-JSON Transformation - Group and structure text based on JSON templates with placeholders - Extract information from AI-generated text into structured JSON formats - Support for any arbitrary JSON structure with nested placeholders - Intelligent extraction of key-value pairs from text - Process AI outputs into structured data for downstream applications ## Getting Started ### Installation ```bash npm install ``` ### Running the server ```bash npm start ``` For development with hot reloading: ```bash npm run dev:watch ``` ## Usage This MCP server provides two main tools: ### 1. Group Text by JSON (`group-text-by-json`) This tool takes a JSON template with placeholders and generates a prompt for an AI to group text according to the template's structure. ```json { "template": "{ \"type\": \"<type>\", \"text\": \"<text>\" }" } ``` The tool analyzes the template, extracts placeholder keys, and returns a prompt that guides the AI to extract information in a key-value format. ### 2. Text to JSON (`text-to-json`) This tool takes the grouped text output from the previous step and converts it into a structured JSON object based on the original template. ```json { "template": "{ \"type\": \"<type>\", \"text\": \"<text>\" }", "text": "type: pen\ntext: This is a blue pen" } ``` It extracts key-value pairs from the text and structures them according to the template. ## Example Workflow 1. **Define a JSON template with placeholders:** ```json { "item": { "name": "<name>", "price": "<price>", "description": "<description>" } } ``` 2. **Use `group-text-by-json` to create a prompt for AI:** - The tool identifies placeholder keys: name, price, description - Generates a prompt instructing the AI to group information by these keys 3. **Send the prompt to an AI model and receive grouped text:** ``` name: Blue Pen price: $2.99 description: A smooth-writing ballpoint pen with blue ink ``` 4. **Use `text-to-json` to convert the grouped text to JSON:** - Result: ```json { "item": { "name": "Blue Pen", "price": "$2.99", "description": "A smooth-writing ballpoint pen with blue ink" } } ``` ## Template Format Templates can include placeholders anywhere within a valid JSON structure: - Use angle brackets to define placeholders: `<name>`, `<type>`, `<price>`, etc. - The template must be a valid JSON string - Placeholders can be at any level of nesting - Supports complex nested structures Example template with nested placeholders: ```json { "product": { "details": { "name": "<name>", "category": "<category>" }, "pricing": { "amount": "<price>", "currency": "USD" } }, "metadata": { "timestamp": "2023-09-01T12:00:00Z" } } ``` ## Implementation Details The server works by: 1. Analyzing JSON templates to extract placeholder keys 2. Generating prompts that guide AI models to extract information by these keys 3. Parsing AI-generated text to extract key-value pairs 4. Reconstructing JSON objects based on the original template structure ## Development ### Prerequisites - Node.js v18 or higher - npm or yarn ### Build and Run ```bash # Install dependencies npm install # Build the project npm run build # Run the server npm start # Development with hot reloading npm run dev:watch ``` ### Custom Hot Reloading This project includes a custom hot reloading setup that combines: - **nodemon**: Watches for file changes in the src directory and rebuilds TypeScript files - **browser-sync**: Automatically refreshes the browser when build files change - **Concurrent execution**: Runs both services simultaneously with output synchronization The setup is configured in: - `nodemon.json`: Controls TypeScript watching and rebuilding - `package.json`: Uses concurrently to run nodemon and browser-sync together To use the custom hot reloading feature: ```bash npm run dev:watch ``` This creates a development environment where: 1. TypeScript files are automatically rebuilt when changed 2. The MCP server restarts with the updated code 3. Connected browsers refresh to show the latest changes ### Using with MCP Inspector You can use the MCP Inspector for debugging: ```bash npm run dev ``` This runs the server with the MCP Inspector for visual debugging of requests and responses. ``` -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- ``` import { defineConfig } from "eslint/config"; import globals from "globals"; import tseslint from "typescript-eslint"; export default defineConfig([ { files: ["**/*.{js,mjs,cjs,ts}"] }, { files: ["**/*.{js,mjs,cjs,ts}"], languageOptions: { globals: globals.browser } }, tseslint.configs.recommended, ]); ``` -------------------------------------------------------------------------------- /nodemon.json: -------------------------------------------------------------------------------- ```json { "watch": ["src/**/*.ts"], "ext": "ts", "ignore": ["src/**/*.spec.ts", "build/"], "exec": "mcp-inspector node build/index.js", "events": { "restart": "tsc && chmod 755 build/index.js && echo 'Built TypeScript...'", "start": "tsc && chmod 755 build/index.js && echo 'Built TypeScript (initial)...'" } } ``` -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- ```json { "compilerOptions": { "target": "ES2022", "module": "Node16", "moduleResolution": "Node16", "outDir": "./build", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"], "exclude": ["node_modules"] } ``` -------------------------------------------------------------------------------- /src/common/constants.ts: -------------------------------------------------------------------------------- ```typescript import { ServerCapabilities } from "@modelcontextprotocol/sdk/types.js"; const VERSION = "0.0.1"; const MCP_SERVER_NAME = "custom-context-mcp"; const TOOL_NAMES = { groupTextByJson: "group-text-by-json", textToJson: "text-to-json", }; const MCP_CAPABILITIES: ServerCapabilities = { tools: {}, }; export { VERSION, MCP_SERVER_NAME, TOOL_NAMES, MCP_CAPABILITIES }; ``` -------------------------------------------------------------------------------- /src/common/types.ts: -------------------------------------------------------------------------------- ```typescript import z from "zod"; const GroupTextByJsonSchema = z.object({ template: z.string().describe("JSON template with placeholders"), }); const TextToJsonSchema = z.object({ template: z.string().describe("JSON template with placeholders"), text: z.string().describe("Groupped text from groupTextByJson tool"), }); export type GroupTextByJsonSchemaType = z.infer<typeof GroupTextByJsonSchema>; export type TextToJsonSchemaType = z.infer<typeof TextToJsonSchema>; export { GroupTextByJsonSchema, TextToJsonSchema }; ``` -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- ```json { "name": "custom-context-mcp", "version": "1.0.0", "description": "", "main": "index.js", "type": "module", "bin": { "custom-context-mcp": "build/index.js" }, "scripts": { "dev": "yarn build && mcp-inspector node build/index.js", "dev:watch": "concurrently \"nodemon\" \"browser-sync start --proxy localhost:6274 --files build/**/* --no-notify --port 3001 --reload-delay 1000\"", "build": "tsc && chmod 755 build/index.js", "check:types": "tsc --noEmit", "check:lint": "eslint . --ext .ts", "check": "npm run check:types && npm run check:lint", "start": "node build/index.js", "test:samples": "yarn build && node build/test-samples.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@modelcontextprotocol/sdk": "^1.8.0", "zod": "^3.24.2", "zod-to-json-schema": "^3.24.5" }, "devDependencies": { "@modelcontextprotocol/inspector": "^0.8.1", "@types/node": "^22.14.0", "browser-sync": "^3.0.4", "concurrently": "^9.1.2", "eslint": "^9.24.0", "globals": "^16.0.0", "nodemon": "^3.1.9", "ts-node": "^10.9.2", "typescript": "^5.8.3", "typescript-eslint": "^8.29.0" }, "files": [ "build" ] } ``` -------------------------------------------------------------------------------- /src/common/utils.ts: -------------------------------------------------------------------------------- ```typescript const logger = { info: (...args: any[]) => { const msg = `[INFO] ${args.join(" ")}`; process.stderr.write(`${msg}\n`); }, debug: (...args: any[]) => { const msg = `\x1b[36m[DEBUG]\x1b[0m ${args.join(" ")}`; process.stderr.write(`${msg}\n`); }, warn: (...args: any[]) => { const msg = `\x1b[33m[WARN]\x1b[0m ${args.join(" ")}`; process.stderr.write(`${msg}\n`); }, error: (...args: any[]) => { const msg = `\x1b[31m[ERROR]\x1b[0m ${args.join(" ")}`; process.stderr.write(`${msg}\n`); }, }; function deepObjectKeys(obj: any, onlyPlaceholders: boolean = false): string[] { const keys: string[] = []; function traverseObject(obj: Record<string, any>, prefix: string = "") { if (typeof obj !== "object" || !obj) return; for (const objKey of Object.keys(obj)) { const currObj = obj[objKey] as Record<string, any> | string; const keyName = prefix ? `${prefix}.${objKey}` : objKey; if (onlyPlaceholders) { const bracketsRegex = /<[^>]+>/gi; if (typeof currObj === "string" && bracketsRegex.test(currObj)) { keys.push(keyName); } } else { keys.push(keyName); } if (typeof currObj === "object" && !Array.isArray(currObj) && !!currObj) { traverseObject(currObj, objKey); } } } traverseObject(obj); return keys; } function extractKeyValuesFromText(text: string, keys: string[]) { const regex = new RegExp(`(${keys.join("|")}): (.*?)(\n|$)`, "gi"); const matches = text.match(regex); if (!matches) { return {}; } const result: Record<string, string> = {}; matches.forEach((match) => { const [key, value] = match.split(":"); const extractedKey = key.trim(); const extractedValues = value.trim(); if (extractedKey) { result[extractedKey] = extractedValues ?? ""; } }); return result; } export { logger, deepObjectKeys, extractKeyValuesFromText }; ``` -------------------------------------------------------------------------------- /src/common/tools.ts: -------------------------------------------------------------------------------- ```typescript import { deepObjectKeys, extractKeyValuesFromText, logger } from "./utils.js"; const groupTextByJsonTool = (template: string) => { if (!template) { throw new Error("Both template and text are required"); } try { logger.info("Template:", template); let objectKeys: string[] = []; try { const templateObj = JSON.parse(template); objectKeys = deepObjectKeys(templateObj, true); } catch (parseError) { logger.error("Failed to parse template:", parseError); throw new Error(`Invalid template format: ${parseError}`); } const resultPrompt = ` You are a helpful assistant that groups text based on JSON keys. Here are the keys in the template: ${objectKeys.join(", ")}. Please group the text based on the keys. and give me the result in raw text. Don't give it in JSON format or object format. It should be in the following format: Format: <key>: <corresponding text found in the text> Here's an example: sentence: The MacBook Pro costs $2,499. result: brand: MacBook price: $2,499 description: The MacBook Pro is a powerful laptop with a Retina display. `; return { content: [ { type: "text", text: resultPrompt, }, ], }; } catch (error) { logger.error("Error processing template:", error); throw new Error(`Failed to process template: ${error}`); } }; const textToJsonTool = (template: string, text: string) => { if (!template || !text) { throw new Error("Both template and text are required"); } try { const templateObj = JSON.parse(template); const templateKeys = deepObjectKeys(templateObj, true); const jsonResult = extractKeyValuesFromText(text, templateKeys); const resultPrompt = ` Print this JSON result in JSON format. JSON result: ${JSON.stringify(jsonResult)} `; return { content: [ { type: "text", text: resultPrompt, }, ], }; } catch (error) { logger.error("Error processing template:", error); throw new Error(`Failed to process template: ${error}`); } }; export { groupTextByJsonTool, textToJsonTool }; ``` -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- ```typescript import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js"; import { zodToJsonSchema } from "zod-to-json-schema"; import { logger } from "./common/utils.js"; import { GroupTextByJsonSchema, GroupTextByJsonSchemaType, TextToJsonSchema, TextToJsonSchemaType, } from "./common/types.js"; import { groupTextByJsonTool, textToJsonTool } from "./common/tools.js"; import { MCP_CAPABILITIES, MCP_SERVER_NAME, TOOL_NAMES, VERSION, } from "./common/constants.js"; const server = new Server( { name: MCP_SERVER_NAME, version: VERSION, }, { capabilities: MCP_CAPABILITIES, } ); server.setRequestHandler(ListToolsRequestSchema, async () => { logger.info("[MCP] Received tools/list request"); const response = { tools: [ { name: TOOL_NAMES.groupTextByJson, description: "Gives a prompt text for AI to group text based on JSON placeholders. This tool accepts a JSON template with placeholders.", inputSchema: zodToJsonSchema(GroupTextByJsonSchema), }, { name: TOOL_NAMES.textToJson, description: `Converts groupped text from ${TOOL_NAMES.groupTextByJson} tool to JSON. This tool accepts a JSON template with placeholders and groupped text from ${TOOL_NAMES.groupTextByJson} tool.`, inputSchema: zodToJsonSchema(TextToJsonSchema), }, ], }; return response; }); server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params; logger.info(`[MCP] Received tools/call request for tool: ${name}`); logger.debug(`[MCP] Tool arguments: ${JSON.stringify(args, null, 2)}`); if (!args) { throw new Error("Arguments are required"); } switch (name) { case TOOL_NAMES.groupTextByJson: const groupTextByJsonArgs = args as GroupTextByJsonSchemaType; return groupTextByJsonTool(groupTextByJsonArgs.template); case TOOL_NAMES.textToJson: const textToJsonArgs = args as TextToJsonSchemaType; return textToJsonTool(textToJsonArgs.template, textToJsonArgs.text); default: throw new Error(`Unknown tool: ${name}`); } }); async function runServer() { try { logger.info("Initializing MCP Server..."); const transport = new StdioServerTransport(); logger.info("Connecting to transport..."); await server.connect(transport); logger.info("Custom Context MCP Server running on stdio"); logger.info( "Server information:", JSON.stringify({ name: MCP_SERVER_NAME, tools: [TOOL_NAMES.groupTextByJson], }) ); logger.info("MCP Server is ready to accept requests"); process.on("SIGINT", () => { logger.info("Received SIGINT signal, shutting down..."); process.exit(0); }); process.on("SIGTERM", () => { logger.info("Received SIGTERM signal, shutting down..."); process.exit(0); }); process.on("uncaughtException", (error: Error) => { logger.error("Uncaught exception:", error); }); } catch (error) { logger.error("Fatal error during server initialization:", error); process.exit(1); } } runServer().catch((error) => { logger.error("Fatal error while running server:", error); if (error instanceof Error) { logger.error("Stack trace:", error.stack); } process.exit(1); }); ```