# MCP Self-Registering Framework Guide > **FOR AI CODING ASSISTANTS**: This is your guide to working with the MCP (Model Context Protocol) self-registering framework in this codebase. ## 🚨 **CRITICAL: READ THIS FIRST** This MCP implementation uses a **self-registering framework** with **barrel exports** to eliminate boilerplate. You can add/remove tools and prompts by creating files + adding one line to a barrel export - **minimal manual work required**. ## 📋 **FRAMEWORK OVERVIEW** **Architecture**: Self-registration with barrel exports **Language**: TypeScript with official `@modelcontextprotocol/sdk` **Transport**: HTTP via `mcp-http-server` **Discovery**: Self-registration triggered by barrel exports ## 🏗️ **CORE FRAMEWORK PRINCIPLES** ### **1. Self-Registration Pattern** - **Tools/prompts register themselves** when imported - **Barrel exports trigger imports** → Automatic registration - **Registry stores everything** → Framework loads from registry ### **2. Directory-Based Organization** ``` src/mcp/ ├── framework/ # Self-registering framework │ ├── index.ts # Main exports │ ├── core.ts # Framework logic │ ├── registry.ts # In-memory registry │ ├── auto-register.ts # Registration helpers │ └── auto-import.ts # Auto-imports barrel exports ├── tools/ # Self-registering tools │ ├── index.ts # Barrel export (add tools here!) │ ├── get_branch_comparison/ │ │ ├── config.ts # Config + self-registration │ │ └── handler.ts # Handler function │ └── submit_bulk_ai_comments/ │ ├── config.ts # Config + self-registration │ └── handler.ts # Handler function ├── prompts/ # Self-registering prompts │ ├── index.ts # Barrel export (add prompts here!) │ └── code_review.ts # Prompt + self-registration ├── server-framework.ts # Framework-based server factory ├── integration.ts # VSCode extension integration └── index.ts # Main MCP exports ``` ### **3. Self-Registration Convention** Every tool/prompt file must: - Import `registerTool` or `registerPrompt` - Call the registration function with its definition - Export its config as default ## ✅ **ADDING NEW TOOLS (2 steps)** ### **Step 1: Create Tool Files** **`src/mcp/tools/my_awesome_tool/config.ts`**: ```typescript import { registerTool } from '../../framework/auto-register'; import handler from './handler'; const config = { description: 'Does something awesome with the code', inputSchema: { type: 'object', properties: { input: { type: 'string', description: 'What to do' } }, required: ['input'] } }; // Self-register this tool ✨ registerTool('my_awesome_tool', config, handler); export default config; ``` **`src/mcp/tools/my_awesome_tool/handler.ts`**: ```typescript import { McpContext } from '../../server-framework'; export default async function handler(args: any, context: McpContext): Promise { const { reviewStateManager, workspaceRoot } = context; // Your awesome logic here return { content: [{ type: 'text', text: `Processed: ${args.input}` }] }; } ``` ### **Step 2: Add to Barrel Export** Add **one line** to `src/mcp/tools/index.ts`: ```typescript export * from './my_awesome_tool/config'; ``` **Done!** ✨ Your tool is now available to AI agents. ## ✅ **ADDING NEW PROMPTS (2 steps)** ### **Step 1: Create Prompt File** **`src/mcp/prompts/my_awesome_prompt.ts`**: ```typescript import { registerPrompt } from '../framework/auto-register'; const myPrompt = { description: 'Provides awesome code analysis', prompt: `You are an expert code reviewer. Analyze the code and provide awesome insights...` }; // Self-register this prompt ✨ registerPrompt('my_awesome_prompt', myPrompt); export default myPrompt; ``` ### **Step 2: Add to Barrel Export** Add **one line** to `src/mcp/prompts/index.ts`: ```typescript export * from './my_awesome_prompt'; ``` **Done!** ✨ Your prompt is now available to AI agents. ## 🚀 **HOW IT WORKS** 1. **Self-Registration**: Each tool/prompt calls `registerTool()` or `registerPrompt()` when imported 2. **Barrel Exports**: `tools/index.ts` and `prompts/index.ts` export all tools/prompts 3. **Auto-Import**: `auto-import.ts` imports barrel exports, triggering self-registration 4. **Registry**: In-memory registry stores all registered tools/prompts 5. **Framework**: Loads from registry instead of filesystem (bundle-friendly!) ## 🔧 **FRAMEWORK INTERNALS** ### **Context Object** Every handler receives a `McpContext` object: ```typescript interface McpContext { reviewStateManager?: any; // Access to extension's review state commentProcessor?: any; // Comment processing functionality workspaceRoot?: string; // Current workspace directory } ``` ### **Registry System** ```typescript // Registry stores all registered items const toolRegistry = new Map(); const promptRegistry = new Map(); // Self-registration functions export function registerTool(name: string, config: any, handler: Function) { toolRegistry.set(name, { config, handler }); } export function registerPrompt(name: string, prompt: any) { promptRegistry.set(name, prompt); } ``` ## 🚫 **WHAT NOT TO DO** ### **NEVER:** 1. **Manually register tools/prompts** - They self-register when imported 2. **Modify framework core files** unless adding core functionality 3. **Skip barrel exports** - Tools/prompts won't be imported without them 4. **Use different export patterns** - Must follow the self-registration convention 5. **Import tools/prompts directly** - Use the framework's registry ### **AVOID:** 1. **Complex file structures** - Keep tools in `tool_name/config.ts` + `tool_name/handler.ts` 2. **Circular dependencies** - Tools should be self-contained 3. **Heavy imports** - Keep tool files lightweight for fast loading ## 🛠️ **DEBUGGING** ### **Check Registration** ```typescript // See what's registered import { registry } from './framework'; console.log('Tools:', Array.from(registry.getTools().keys())); console.log('Prompts:', Array.from(registry.getPrompts().keys())); ``` ### **Test Tools Directly** ```typescript // Test your tool handler import handler from './tools/my_tool/handler'; import { McpContext } from './server-framework'; const context: McpContext = { workspaceRoot: '/path/to/workspace' }; const result = await handler({ input: 'test' }, context); console.log(result); ``` ## 📝 **CURRENT TOOLS & PROMPTS** ### **Tools** - **`get_branch_comparison`** - Get structured diff data from specified workspace branch review (requires `workspaceRoot` parameter) - **`submit_bulk_ai_comments`** - Submit multiple AI-generated comments at once ### **Prompts** - **`code_review`** - Comprehensive code review covering correctness, security, performance ## 🎯 **BEST PRACTICES** ### **Tool Design** 1. **Single Responsibility**: Each tool should do one thing well 2. **Clear Schema**: Define all input parameters with descriptions 3. **Error Handling**: Handle edge cases gracefully 4. **Context Usage**: Leverage the context object for extension integration ### **Prompt Design** 1. **Specific Instructions**: Provide clear, actionable guidance 2. **Structured Output**: Request formatted responses with code blocks 3. **Context Awareness**: Consider the development workflow ### **File Organization** 1. **Consistent Structure**: `tool_name/config.ts` + `tool_name/handler.ts` 2. **Descriptive Names**: Use clear, descriptive names for tools/prompts 3. **Documentation**: Include JSDoc comments for all exports 4. **Type Safety**: Use TypeScript interfaces and types ## 🚀 **FRAMEWORK BENEFITS** ### **For Developers** - **Minimal Boilerplate**: Just create files + one barrel export line - **Self-Registration**: No manual wiring or configuration - **Bundle-Friendly**: Works with Bun, webpack, esbuild, etc. - **Type Safety**: Full TypeScript support ### **For AI Agents** - **Consistent Interface**: All tools follow the same pattern - **Self-Documenting**: Tool schemas provide clear parameter definitions - **Easy Extension**: Add new capabilities with minimal effort ## 🆘 **WHEN IN DOUBT** 1. **Follow the Pattern**: Look at existing tools/prompts for examples 2. **Check Barrel Exports**: Make sure your tool/prompt is exported 3. **Test Registration**: Verify your tool appears in the registry 4. **Keep It Simple**: Start with basic functionality and iterate Remember: **The framework handles all the complexity - you just focus on the tool/prompt logic and add one line to the barrel export!**