#
tokens: 166658/50000 1/41 files (page 4/4)
lines: on (toggle) GitHub
raw markdown copy reset
This is page 4 of 4. Use http://codebase.md/crazyrabbitltc/mcp-vibecoder?lines=true&page={x} to view the full context.

# Directory Structure

```
├── .gitignore
├── bun.lockb
├── debug.js
├── docs
│   └── mcp-sdk-improvements.md
├── documents
│   ├── test-feature
│   │   └── prd.md
│   └── test-feature-custom.md
├── instructions
│   ├── checklist.md
│   ├── Impl.md
│   ├── mcp_sdk_improvements.md
│   ├── mcp_server_improvements.md
│   ├── plan.md
│   ├── PRD.md
│   └── solidity_tic_tac_toe_project.md
├── MCP-docs.txt
├── MCP-Typescript-readme.txt
├── package-lock.json
├── package.json
├── README.md
├── repomix-output.txt
├── src
│   ├── clarification.ts
│   ├── document-storage.ts
│   ├── documentation.ts
│   ├── errors.ts
│   ├── index-updated.ts
│   ├── index.ts
│   ├── mcp-server.ts
│   ├── phases.ts
│   ├── registry.ts
│   ├── resource-handlers.ts
│   ├── schemas.ts
│   ├── storage.ts
│   ├── templates
│   │   ├── impl-template.md
│   │   └── prd-template.md
│   ├── test-mcp-improved.js
│   ├── tool-handlers.ts
│   ├── types.ts
│   ├── utils.ts
│   └── validators.ts
├── test-document-storage.js
├── test-document-tools.js
├── test-mcp.js
├── tsconfig.build.json
└── tsconfig.json
```

# Files

--------------------------------------------------------------------------------
/repomix-output.txt:
--------------------------------------------------------------------------------

```
    1 | This file is a merged representation of the entire codebase, combining all repository files into a single document.
    2 | Generated by Repomix on: 2025-03-23T02:06:33.503Z
    3 | 
    4 | ================================================================
    5 | File Summary
    6 | ================================================================
    7 | 
    8 | Purpose:
    9 | --------
   10 | This file contains a packed representation of the entire repository's contents.
   11 | It is designed to be easily consumable by AI systems for analysis, code review,
   12 | or other automated processes.
   13 | 
   14 | File Format:
   15 | ------------
   16 | The content is organized as follows:
   17 | 1. This summary section
   18 | 2. Repository information
   19 | 3. Directory structure
   20 | 4. Multiple file entries, each consisting of:
   21 |   a. A separator line (================)
   22 |   b. The file path (File: path/to/file)
   23 |   c. Another separator line
   24 |   d. The full contents of the file
   25 |   e. A blank line
   26 | 
   27 | Usage Guidelines:
   28 | -----------------
   29 | - This file should be treated as read-only. Any changes should be made to the
   30 |   original repository files, not this packed version.
   31 | - When processing this file, use the file path to distinguish
   32 |   between different files in the repository.
   33 | - Be aware that this file may contain sensitive information. Handle it with
   34 |   the same level of security as you would the original repository.
   35 | 
   36 | Notes:
   37 | ------
   38 | - Some files may have been excluded based on .gitignore rules and Repomix's
   39 |   configuration.
   40 | - Binary files are not included in this packed representation. Please refer to
   41 |   the Repository Structure section for a complete list of file paths, including
   42 |   binary files.
   43 | 
   44 | Additional Info:
   45 | ----------------
   46 | 
   47 | ================================================================
   48 | Directory Structure
   49 | ================================================================
   50 | docs/
   51 |   mcp-sdk-improvements.md
   52 | instructions/
   53 |   checklist.md
   54 |   Impl.md
   55 |   mcp_sdk_improvements.md
   56 |   mcp_server_improvements.md
   57 |   plan.md
   58 |   PRD.md
   59 |   solidity_tic_tac_toe_project.md
   60 | src/
   61 |   templates/
   62 |     impl-template.md
   63 |     prd-template.md
   64 |   clarification.ts
   65 |   documentation.ts
   66 |   errors.ts
   67 |   index-updated.ts
   68 |   index.ts
   69 |   mcp-server.ts
   70 |   phases.ts
   71 |   registry.ts
   72 |   resource-handlers.ts
   73 |   schemas.ts
   74 |   storage.ts
   75 |   test-mcp-improved.js
   76 |   tool-handlers.ts
   77 |   types.ts
   78 |   utils.ts
   79 |   validators.ts
   80 | .gitignore
   81 | debug.js
   82 | MCP-docs.txt
   83 | MCP-Typescript-readme.txt
   84 | package.json
   85 | README.md
   86 | test-mcp.js
   87 | tsconfig.build.json
   88 | tsconfig.json
   89 | 
   90 | ================================================================
   91 | Files
   92 | ================================================================
   93 | 
   94 | ================
   95 | File: docs/mcp-sdk-improvements.md
   96 | ================
   97 | # MCP SDK Implementation Improvements
   98 | 
   99 | ## Overview
  100 | 
  101 | This document outlines the improvements made to the Vibe-Coder MCP server implementation to better align with the MCP TypeScript SDK best practices and improve overall code quality, maintainability, and type safety.
  102 | 
  103 | ## Key Improvements
  104 | 
  105 | ### 1. Tool Handler Registry
  106 | 
  107 | We replaced the large switch statement in the main file with a tool handler registry that maps tool names to their handler functions:
  108 | 
  109 | ```typescript
  110 | // Before (in index.ts)
  111 | server.setRequestHandler(CallToolRequestSchema, async (request) => {
  112 |   try {
  113 |     switch (request.params.name) {
  114 |       case "start_feature_clarification": {
  115 |         // Implementation...
  116 |       }
  117 |       case "provide_clarification": {
  118 |         // Implementation...
  119 |       }
  120 |       // Many more cases...
  121 |     }
  122 |   } catch (error) {
  123 |     // Error handling...
  124 |   }
  125 | });
  126 | 
  127 | // After
  128 | // In registry.ts
  129 | export class ToolRegistry {
  130 |   private handlers: Map<string, ToolHandler> = new Map();
  131 |   
  132 |   register<T>(name: string, handler: ToolHandler<T>): void {
  133 |     this.handlers.set(name, handler);
  134 |   }
  135 |   
  136 |   async execute(name: string, params: any): Promise<any> {
  137 |     const handler = this.getHandler(name);
  138 |     if (!handler) {
  139 |       return createToolErrorResponse(`Unknown tool "${name}"`);
  140 |     }
  141 |     return await handler(params);
  142 |   }
  143 | }
  144 | 
  145 | // In index-updated.ts
  146 | server.setRequestHandler(CallToolRequestSchema, async (request) => {
  147 |   try {
  148 |     const toolName = request.params.name;
  149 |     const toolArguments = request.params.arguments || {};
  150 |     return await toolRegistry.execute(toolName, toolArguments);
  151 |   } catch (error) {
  152 |     // Improved error handling...
  153 |   }
  154 | });
  155 | ```
  156 | 
  157 | ### 2. Robust Resource URI Handling
  158 | 
  159 | We implemented a robust resource URI handling mechanism using a `ResourceRegistry` class:
  160 | 
  161 | ```typescript
  162 | // In registry.ts
  163 | export class ResourceRegistry {
  164 |   private resources: ResourceRegistryEntry[] = [];
  165 |   
  166 |   register(template: ResourceTemplate, handler: ResourceHandler): void {
  167 |     this.resources.push({ template, handler });
  168 |   }
  169 |   
  170 |   findMatch(uri: string): { handler: ResourceHandler; params: Record<string, string> } | undefined {
  171 |     const url = new URL(uri);
  172 |     for (const { template, handler } of this.resources) {
  173 |       const match = this.matchTemplate(url, template);
  174 |       if (match) {
  175 |         return { handler, params: match };
  176 |       }
  177 |     }
  178 |     return undefined;
  179 |   }
  180 | }
  181 | 
  182 | // In index-updated.ts
  183 | server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
  184 |   try {
  185 |     const uri = request.params.uri;
  186 |     const match = resourceRegistry.findMatch(uri);
  187 |     if (match) {
  188 |       return await match.handler(new URL(uri), match.params);
  189 |     }
  190 |     return createErrorResponse(ErrorCode.RESOURCE_NOT_FOUND, `Resource not found: ${uri}`);
  191 |   } catch (error) {
  192 |     // Improved error handling...
  193 |   }
  194 | });
  195 | ```
  196 | 
  197 | ### 3. Improved Error Handling
  198 | 
  199 | We standardized error handling across the codebase with consistent JSON-RPC 2.0 error responses:
  200 | 
  201 | ```typescript
  202 | // In errors.ts
  203 | export enum ErrorCode {
  204 |   // JSON-RPC 2.0 Standard Error Codes
  205 |   PARSE_ERROR = -32700,
  206 |   INVALID_REQUEST = -32600,
  207 |   METHOD_NOT_FOUND = -32601,
  208 |   INVALID_PARAMS = -32602,
  209 |   INTERNAL_ERROR = -32603,
  210 |   
  211 |   // Custom Error Codes
  212 |   VALIDATION_ERROR = -32000,
  213 |   RESOURCE_NOT_FOUND = -32001,
  214 |   // More custom error codes...
  215 | }
  216 | 
  217 | export const createErrorResponse = (
  218 |   code: ErrorCode, 
  219 |   message: string, 
  220 |   data?: any
  221 | ): ErrorResponse => {
  222 |   return {
  223 |     error: {
  224 |       code,
  225 |       message,
  226 |       data
  227 |     }
  228 |   };
  229 | };
  230 | 
  231 | export const createToolErrorResponse = (
  232 |   message: string, 
  233 |   details?: any
  234 | ): ToolErrorResponse => {
  235 |   return {
  236 |     content: [{
  237 |       type: "text",
  238 |       text: `Error: ${message}`
  239 |     }],
  240 |     isError: true
  241 |   };
  242 | };
  243 | ```
  244 | 
  245 | ### 4. Stronger Type Safety
  246 | 
  247 | We improved type safety throughout the codebase with Zod schemas and branded types:
  248 | 
  249 | ```typescript
  250 | // In schemas.ts
  251 | // Branded types for IDs
  252 | export type FeatureId = string & { readonly _brand: unique symbol };
  253 | export type PhaseId = string & { readonly _brand: unique symbol };
  254 | export type TaskId = string & { readonly _brand: unique symbol };
  255 | 
  256 | // Zod schemas for validation
  257 | export const FeatureSchema = z.object({
  258 |   id: z.string().refine(isFeatureId, "Invalid feature ID format"),
  259 |   name: z.string().min(2).max(100),
  260 |   // More fields...
  261 | });
  262 | 
  263 | // Type guards
  264 | export const isFeatureId = (id: string): id is FeatureId => id.startsWith('feature-');
  265 | 
  266 | // ID creators
  267 | export const createFeatureId = (id: string): FeatureId => {
  268 |   if (!isFeatureId(id)) throw new Error(`Invalid feature ID format: ${id}`);
  269 |   return id as FeatureId;
  270 | };
  271 | 
  272 | // In utils.ts
  273 | export function generateFeatureId(): FeatureId {
  274 |   const randomPart = Math.random().toString(36).substring(2, 10);
  275 |   return createFeatureId(`feature-${randomPart}`);
  276 | }
  277 | ```
  278 | 
  279 | ### 5. Modular Code Structure
  280 | 
  281 | We reorganized the codebase into more modular components with clear separation of concerns:
  282 | 
  283 | - `registry.ts` - Tool and resource registries
  284 | - `tool-handlers.ts` - Tool handler implementations
  285 | - `resource-handlers.ts` - Resource handler implementations
  286 | - `errors.ts` - Error handling utilities
  287 | - `schemas.ts` - Type definitions and validation schemas
  288 | 
  289 | ## Benefits
  290 | 
  291 | 1. **Improved Maintainability**: The modular code structure makes it easier to understand, maintain, and extend the codebase.
  292 | 
  293 | 2. **Better Type Safety**: Branded types and Zod schemas provide stronger type checking and runtime validation.
  294 | 
  295 | 3. **Consistent Error Handling**: Standardized error responses across the codebase with proper JSON-RPC 2.0 error codes.
  296 | 
  297 | 4. **More Robust URI Handling**: Proper URI template matching for resources following MCP best practices.
  298 | 
  299 | 5. **Cleaner Code**: Separation of concerns between different components and elimination of large switch statements.
  300 | 
  301 | ## Testing
  302 | 
  303 | The improvements have been tested with a comprehensive test script (`test-mcp-improved.js`) that verifies the functionality of:
  304 | 
  305 | - Tool registration and execution
  306 | - Resource URI matching and handling
  307 | - Error reporting
  308 | - End-to-end workflows (feature clarification, PRD generation, etc.)
  309 | 
  310 | ## Conclusion
  311 | 
  312 | These improvements bring the Vibe-Coder MCP server implementation more in line with MCP TypeScript SDK best practices while also improving overall code quality, maintainability, and type safety.
  313 | 
  314 | ================
  315 | File: instructions/checklist.md
  316 | ================
  317 | # Vibe-Coder MCP Server Implementation Checklist
  318 | 
  319 | ## Step 1: Server Configuration and Core Structure
  320 | - [x] Update server metadata and name
  321 | - [x] Define core data types (Feature, ClarificationResponse, Phase, Task)
  322 | - [x] Create in-memory storage for features and projects
  323 | - [x] Set up directory structure and file organization
  324 | - [x] Implement basic utilities (generateId, etc.)
  325 | 
  326 | ## Step 2: Feature Clarification Implementation
  327 | - [x] Create tool for initiating feature clarification
  328 | - [x] Implement tool for receiving clarification responses
  329 | - [x] Create resource to retrieve clarification status
  330 | - [x] Add support for structured questioning workflow
  331 | 
  332 | ## Step 3: PRD and Implementation Plan Generation
  333 | - [x] Create tool for generating PRD document
  334 | - [x] Implement tool for creating implementation plan
  335 | - [x] Add helper functions for extracting requirements from clarifications
  336 | - [x] Implement markdown formatting for documentation generation
  337 | - [x] Create template structure for PRDs and implementation plans
  338 | 
  339 | ## Step 4: Phase Management Implementation
  340 | - [x] Implement tool for creating phases
  341 | - [x] Add tool for updating phase status
  342 | - [x] Create tool for managing tasks within phases
  343 | - [x] Implement phase workflow progression logic
  344 | 
  345 | ## Step 5: Resource Implementation
  346 | - [x] Create resources for listing all features
  347 | - [x] Add resources for accessing feature details
  348 | - [x] Implement resources for retrieving PRDs
  349 | - [x] Create resources for retrieving implementation plans
  350 | - [x] Add support for phase and task status viewing
  351 | 
  352 | ## Step 6: Tool Implementation
  353 | - [x] Define all tool schemas and validations
  354 | - [x] Implement error handling for tools
  355 | - [x] Ensure proper argument validation
  356 | - [x] Add support for tool discoverability
  357 | - [x] Test tool invocations with example data
  358 | 
  359 | ## Step 7: Prompt Implementation
  360 | - [ ] Create clarify_feature prompt
  361 | - [ ] Implement generate_prd_template prompt
  362 | - [ ] Add phase_implementation_guide prompt
  363 | - [ ] Ensure prompts are well-structured for LLM use
  364 | 
  365 | ## Testing and Documentation
  366 | - [ ] Test each tool individually
  367 | - [ ] Test complete workflows end-to-end
  368 | - [ ] Create example usage documentation
  369 | - [ ] Add README with setup and usage instructions
  370 | 
  371 | ================
  372 | File: instructions/Impl.md
  373 | ================
  374 | # Vibe-Coder MCP Server Implementation Plan
  375 | 
  376 | This document outlines the step-by-step implementation strategy for building the Vibe-Coder MCP Server using the Model Context Protocol specification for TypeScript. Each phase represents a discrete, focused task with clear checklists, coding standards, and review processes.
  377 | 
  378 | ---
  379 | 
  380 | ## Phase 1: Environment Setup and Repository Initialization
  381 | 
  382 | ### Objectives
  383 | - Set up the development environment and repository.
  384 | - Install required dependencies (including the MCP TypeScript SDK).
  385 | - Establish a working base by validating a simple MCP server.
  386 | 
  387 | ### Tasks
  388 | - [ ] **Repository Initialization:**  
  389 |   - Create a new repository or branch dedicated to the Vibe-Coder feature.
  390 |   - Follow the naming convention: `feature/vibe-coder`.
  391 | - [ ] **Environment Setup:**  
  392 |   - Ensure Node.js and npm are installed.
  393 |   - Install the MCP TypeScript SDK:  
  394 |     ```bash
  395 |     npm install @modelcontextprotocol/sdk
  396 |     ```
  397 | - [ ] **Basic MCP Server Setup:**  
  398 |   - Create a minimal MCP server (e.g., an Echo server) based on the MCP TypeScript examples.
  399 |   - Validate that the server correctly processes simple requests (using `StdioServerTransport` or HTTP with SSE).
  400 | - [ ] **Establish Branching Guidelines:**  
  401 |   - Document and enforce the branch naming convention (e.g., each phase creates a branch off the main feature branch).
  402 | 
  403 | ### Code Style & Practices
  404 | - Use TypeScript best practices.
  405 | - Follow the MCP SDK examples for a clean code structure.
  406 | - Maintain clear commit messages describing changes made.
  407 | 
  408 | ---
  409 | 
  410 | ## Phase 2: Implement Feature Request Clarification Module
  411 | 
  412 | ### Objectives
  413 | - Build a module to interactively engage users to clarify feature requests.
  414 | - Record and structure user responses to refine the feature scope.
  415 | 
  416 | ### Tasks
  417 | - [ ] **Design Clarification Workflow:**  
  418 |   - Define a flow that asks iterative questions and records responses.
  419 |   - Use clear prompts to ensure the user’s requirements are well defined.
  420 | - [ ] **Implement Clarification Module:**  
  421 |   - Create a dedicated TypeScript module (e.g., `clarification.ts`) that:
  422 |     - Sends questions to the user.
  423 |     - Stores responses in a structured format (e.g., JSON).
  424 | - [ ] **Integrate with MCP Tools/Prompts:**  
  425 |   - Utilize MCP prompts to ask clarifying questions if appropriate.
  426 | - [ ] **Testing:**  
  427 |   - Create unit tests that simulate user interactions and verify the response recording.
  428 | 
  429 | ### Checklist
  430 | - [ ] Define a list of initial questions.
  431 | - [ ] Implement response recording with validation.
  432 | - [ ] Integrate and test prompt handling via MCP.
  433 | 
  434 | ---
  435 | 
  436 | ## Phase 3: PRD and Documentation Generation Module
  437 | 
  438 | ### Objectives
  439 | - Automate the generation and saving of PRD documentation.
  440 | - Ensure that the PRD is saved in the correct folder with the proper naming convention.
  441 | 
  442 | ### Tasks
  443 | - [ ] **Template Creation:**  
  444 |   - Develop a Markdown template for the PRD (reuse sections from the PRD document).
  445 | - [ ] **File Generation Module:**  
  446 |   - Create a module (e.g., `docGenerator.ts`) that:
  447 |     - Populates the template with feature details.
  448 |     - Saves the file to `vibe-instructions/` with a name like `01_VibeCoder_PRD.md`.
  449 | - [ ] **Validation:**  
  450 |   - Implement checks to ensure the generated file meets naming and format requirements.
  451 | 
  452 | ### Checklist
  453 | - [ ] Define PRD template sections.
  454 | - [ ] Write file I/O functions to save Markdown files.
  455 | - [ ] Test file generation with dummy data.
  456 | 
  457 | ---
  458 | 
  459 | ## Phase 4: MCP Server Integration and Feature Implementation
  460 | 
  461 | ### Objectives
  462 | - Integrate the clarified feature request and documentation modules into the MCP server.
  463 | - Build the core functionality of the Vibe-Coder using the MCP TypeScript SDK.
  464 | 
  465 | ### Tasks
  466 | - [ ] **Server Initialization:**  
  467 |   - Initialize an MCP server instance using the MCP TypeScript SDK.
  468 |   - Example:
  469 |     ```typescript
  470 |     import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
  471 |     import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
  472 | 
  473 |     const server = new McpServer({
  474 |       name: "Vibe-Coder",
  475 |       version: "1.0.0"
  476 |     });
  477 |     ```
  478 | - [ ] **Integrate Clarification Module:**  
  479 |   - Connect the clarification module to the MCP server’s tool or prompt mechanisms.
  480 | - [ ] **Feature Request Handling:**  
  481 |   - Define MCP tools or resources to process and store feature requests and clarifications.
  482 | - [ ] **Documentation Integration:**  
  483 |   - Link the generated PRD and Implementation Plan documents to the MCP server’s workflow (e.g., as resources that can be fetched by clients).
  484 | - [ ] **Testing:**  
  485 |   - Test server interactions using both local transports (stdio) and, if applicable, HTTP with SSE.
  486 | 
  487 | ### Checklist
  488 | - [ ] Initialize MCP server using the TypeScript SDK.
  489 | - [ ] Integrate the clarification module with MCP prompts.
  490 | - [ ] Validate tool/resource functionality with sample requests.
  491 | - [ ] Ensure documentation files are retrievable by the server.
  492 | 
  493 | ---
  494 | 
  495 | ## Phase 5: Phased Implementation Workflow and Branching
  496 | 
  497 | ### Objectives
  498 | - Establish and enforce the phased development workflow.
  499 | - Ensure each phase’s changes are documented, committed, and reviewed before merging.
  500 | 
  501 | ### Tasks
  502 | - [ ] **Branch Creation:**  
  503 |   - Create a new branch for each phase from the main feature branch (e.g., `phase/clarification`, `phase/documentation`, `phase/integration`).
  504 | - [ ] **Commit Process:**  
  505 |   - Write detailed commit messages that reference the checklist and completed tasks.
  506 | - [ ] **Code Reviews:**  
  507 |   - Request targeted code reviews for each phase.
  508 |   - Share the PRD, phase-specific Implementation Plan, and corresponding code changes.
  509 | - [ ] **Merge and History:**  
  510 |   - Merge phase branches into the feature branch once approved.
  511 |   - Retain phase branches for historical reference.
  512 | 
  513 | ### Checklist
  514 | - [ ] Create and document branch naming conventions.
  515 | - [ ] Write commit message guidelines.
  516 | - [ ] Schedule code reviews for each completed phase.
  517 | - [ ] Merge phase branches after successful review.
  518 | 
  519 | ---
  520 | 
  521 | ## Phase 6: Finalization, Project Summary, and Feature README
  522 | 
  523 | ### Objectives
  524 | - Complete the feature by updating project documentation.
  525 | - Summarize the new functionality and provide usage instructions.
  526 | 
  527 | ### Tasks
  528 | - [ ] **Project README Update:**  
  529 |   - Update the main project README with a summary of the Vibe-Coder feature.
  530 | - [ ] **Feature-Specific README:**  
  531 |   - Create a dedicated README that details:
  532 |     - The new feature’s functionality.
  533 |     - How to use and integrate the Vibe-Coder MCP Server.
  534 |     - References to the PRD and Implementation Plan.
  535 | - [ ] **Final Code Review:**  
  536 |   - Request a comprehensive review covering the entire feature.
  537 |   - Ensure all documentation, tests, and code changes meet the defined standards.
  538 | 
  539 | ### Checklist
  540 | - [ ] Write a project summary for the new feature.
  541 | - [ ] Generate a feature-specific README with detailed instructions.
  542 | - [ ] Conduct a final, comprehensive code review.
  543 | - [ ] Merge final changes into the main branch.
  544 | 
  545 | ---
  546 | 
  547 | ## Summary
  548 | 
  549 | This Implementation Plan breaks down the development of the Vibe-Coder MCP Server into six discrete phases—from environment setup to final documentation and code review. Each phase is accompanied by detailed tasks and checklists, ensuring adherence to the MCP specification for TypeScript and maintaining a clear, organized workflow.
  550 | 
  551 | By following this plan, the development team will be able to iteratively build, test, and review the feature, ensuring that it is robust, well-documented, and compliant with established coding standards and best practices.
  552 | 
  553 | ================
  554 | File: instructions/mcp_sdk_improvements.md
  555 | ================
  556 | # Implementation Plan for MCP SDK Improvements
  557 | 
  558 | ## 1. Replace Switch Statement with Tool Handler Map
  559 | 
  560 | ### Tasks:
  561 | - [x] Create a tool handler type definition in `types.ts`
  562 | - [x] Create a tools registry object that maps tool names to handler functions
  563 | - [x] Refactor the `CallToolRequestSchema` handler to use this registry
  564 | - [x] Add validation and error handling for unknown tools
  565 | - [x] Update tool registration to automatically populate the registry
  566 | - [ ] Test all tools to ensure functionality remains the same
  567 | 
  568 | ## 2. Implement Robust URI Parsing
  569 | 
  570 | ### Tasks:
  571 | - [x] Create a `ResourceRegistry` class that handles URI templates and matching
  572 | - [x] Update resource definitions to use proper URI templates
  573 | - [x] Implement pattern matching for incoming resource URIs
  574 | - [x] Refactor `ReadResourceRequestSchema` handler to use the registry
  575 | - [x] Add validation and error handling for malformed URIs
  576 | - [ ] Test with various URI patterns to ensure correct matching
  577 | 
  578 | ## 3. Improve Error Handling Consistency
  579 | 
  580 | ### Tasks:
  581 | - [x] Define standard error response types following JSON-RPC 2.0 spec
  582 | - [x] Create utility functions for generating consistent error responses
  583 | - [x] Update all error returns to use these utility functions
  584 | - [x] Ensure error codes are appropriate and consistent
  585 | - [x] Add more detailed error messages with context
  586 | - [x] Improve validation error reporting
  587 | - [ ] Test error scenarios to verify consistent responses
  588 | 
  589 | ## 4. Use More Specific Types and Reduce Type Assertions
  590 | 
  591 | ### Tasks:
  592 | - [x] Create Zod schemas for core data structures (Feature, Phase, Task)
  593 | - [x] Implement branded types for identifiers (FeatureId, PhaseId, TaskId)
  594 | - [x] Replace string types with more specific types where appropriate
  595 | - [ ] Eliminate `@ts-ignore` comments by fixing underlying type issues
  596 | - [x] Add runtime type validation at critical boundaries
  597 | - [x] Update function signatures to use the new types
  598 | - [ ] Test type safety with various inputs
  599 | 
  600 | ## Implementation Order and Dependencies
  601 | 
  602 | 1. **First Phase**: Type improvements (foundation for other changes) ✅
  603 |    - Implement specific types and Zod schemas ✅
  604 |    - Remove type assertions where possible ✅
  605 | 
  606 | 2. **Second Phase**: Error handling improvements ✅
  607 |    - Create error utilities ✅
  608 |    - Update error responses to use common format ✅
  609 | 
  610 | 3. **Third Phase**: Resource URI handling ✅
  611 |    - Implement resource registry ✅
  612 |    - Update URI parsing and matching ✅
  613 | 
  614 | 4. **Fourth Phase**: Tool handler refactoring ✅
  615 |    - Create tools registry ✅ 
  616 |    - Refactor call tool request handling ✅
  617 | 
  618 | ## Next Steps
  619 | 
  620 | 1. Testing strategy:
  621 |    - Create unit tests for each component
  622 |    - Test edge cases and error scenarios
  623 |    - Compare outputs before and after changes to ensure consistency
  624 | 
  625 | 2. Create a PR with the changes
  626 |    - Update the documentation
  627 |    - Add examples of using the new APIs
  628 | 
  629 | ================
  630 | File: instructions/mcp_server_improvements.md
  631 | ================
  632 | # Implementation Plan: MCP Server Improvements
  633 | 
  634 | ## Phase 1: Critical Fixes (High Priority)
  635 | 
  636 | ### Task 1: Fix Resource Registry Import
  637 | - [x] Update `index-updated.ts` to import `resourceRegistry` at the top of the file
  638 | - [x] Remove the `require` call from the `ReadResourceRequestSchema` handler
  639 | - [x] Test the handler to ensure it works properly with the imported registry
  640 | 
  641 | ### Task 2: Improve Error Handling
  642 | - [x] Modify `documentation.ts` to throw proper errors when template loading fails
  643 | - [x] Update `clarification.ts` to throw specific errors and return completion objects
  644 | - [x] Add try/catch blocks where necessary to handle these new errors properly
  645 | - [ ] Test the error handling with invalid inputs
  646 | 
  647 | ## Phase 2: Architecture Improvements (Medium Priority)
  648 | 
  649 | ### Task 1: Enhance Tool Registry with Metadata
  650 | - [x] Modify the `ToolRegistry` class in `registry.ts` to store and manage tool metadata
  651 | - [x] Add `listTools()` method to return all registered tools with their metadata
  652 | - [x] Update the `register` method to accept description and input schema
  653 | - [x] Modify `index-updated.ts` to use `toolRegistry.listTools()` in the handler
  654 | 
  655 | ### Task 2: Implement Self-Registration Pattern
  656 | - [ ] Create a new file `tool-registry.ts` to define the tool registration process
  657 | - [ ] Modify each tool handler file to self-register on import
  658 | - [ ] Remove the centralized `registerToolHandlers` function
  659 | - [ ] Repeat the same pattern for resource handlers
  660 | - [ ] Test that all tools and resources are properly registered
  661 | 
  662 | ## Phase 3: Enhance Testing Framework (Medium Priority)
  663 | 
  664 | ### Task 1: Set Up Jest Testing Framework
  665 | - [ ] Install Jest and related dependencies
  666 | - [ ] Configure Jest for TypeScript testing
  667 | - [ ] Create a basic test setup file with server startup/shutdown
  668 | 
  669 | ### Task 2: Migrate Existing Tests to Jest
  670 | - [ ] Convert the `test-mcp-improved.js` to use Jest's test structure
  671 | - [ ] Replace timeouts with proper async/await and promises
  672 | - [ ] Add assertions to verify responses
  673 | 
  674 | ### Task 3: Add Comprehensive Tests
  675 | - [ ] Add tests for error cases and edge conditions
  676 | - [ ] Test URI matching with various patterns
  677 | - [ ] Test tool execution with valid and invalid inputs
  678 | - [ ] Test resource handling with various URIs
  679 | 
  680 | ## Phase 4: Additional Improvements (Lower Priority)
  681 | 
  682 | ### Task 1: Implement Better Templating
  683 | - [ ] Research and select an appropriate templating engine
  684 | - [ ] Update `documentation.ts` to use the selected templating engine
  685 | - [ ] Create improved templates with proper variable handling
  686 | 
  687 | ### Task 2: Ensure Consistent Code Style
  688 | - [ ] Apply consistent naming conventions throughout the codebase
  689 | - [ ] Add JSDoc comments to all functions and classes
  690 | - [ ] Set up a code formatter like Prettier
  691 | 
  692 | ## Implementation Steps
  693 | 
  694 | ### For Phase 1:
  695 | 1. Fix Resource Registry Import: ✅
  696 |    ```typescript
  697 |    // At the top of index-updated.ts
  698 |    import { toolRegistry, resourceRegistry } from './registry.js';
  699 |    
  700 |    // In the ReadResourceRequestSchema handler
  701 |    const match = resourceRegistry.findMatch(uri);
  702 |    ```
  703 | 
  704 | 2. Improve Error Handling: ✅
  705 |    ```typescript
  706 |    // In documentation.ts
  707 |    function loadTemplate(templateName: string): string {
  708 |      try {
  709 |        return fs.readFileSync(templatePath, 'utf-8');
  710 |      } catch (error) {
  711 |        throw new Error(`Failed to load template ${templateName}: ${error}`);
  712 |      }
  713 |    }
  714 |    
  715 |    // In clarification.ts
  716 |    export function getNextClarificationQuestion(feature: Feature): string | { done: true } {
  717 |      if (!feature.clarificationResponses) {
  718 |        throw new Error(`Feature is missing clarificationResponses array: ${feature.id}`);
  719 |      }
  720 |      
  721 |      if (feature.clarificationResponses.length >= DEFAULT_CLARIFICATION_QUESTIONS.length) {
  722 |        return { done: true };
  723 |      }
  724 |      
  725 |      return DEFAULT_CLARIFICATION_QUESTIONS[feature.clarificationResponses.length];
  726 |    }
  727 |    ```
  728 | 
  729 | ### For Phase 2:
  730 | 1. Enhance Tool Registry: ✅
  731 |    ```typescript
  732 |    // In registry.ts
  733 |    export class ToolRegistry {
  734 |      private handlers: Map<string, ToolHandler> = new Map();
  735 |      private toolMetadata: Map<string, { description: string; inputSchema: any }> = new Map();
  736 |    
  737 |      register<T>(
  738 |        name: string,
  739 |        handler: ToolHandler<T>,
  740 |        description: string,
  741 |        inputSchema: any
  742 |      ): void {
  743 |        this.handlers.set(name, handler);
  744 |        this.toolMetadata.set(name, { description, inputSchema });
  745 |      }
  746 |    
  747 |      // ... existing methods ...
  748 |    
  749 |      listTools(): { name: string; description: string; inputSchema: any }[] {
  750 |        return Array.from(this.handlers.keys()).map((name) => {
  751 |          const metadata = this.toolMetadata.get(name);
  752 |          return {
  753 |            name,
  754 |            description: metadata?.description || "No description provided.",
  755 |            inputSchema: metadata?.inputSchema || {},
  756 |          };
  757 |        });
  758 |      }
  759 |    }
  760 |    
  761 |    // In index-updated.ts
  762 |    server.setRequestHandler(ListToolsRequestSchema, async () => {
  763 |      return {
  764 |        tools: toolRegistry.listTools(),
  765 |      };
  766 |    });
  767 |    ```
  768 | 
  769 | ## Timeline and Dependencies
  770 | 
  771 | 1. Phase 1 (1-2 days): ✅
  772 |    - Resource registry fix: 0.5 day ✅
  773 |    - Error handling improvements: 1-1.5 days ✅
  774 |    - No dependencies
  775 | 
  776 | 2. Phase 2 (2-3 days): 🔄
  777 |    - Tool registry enhancements: 1-1.5 days ✅
  778 |    - Self-registration pattern: 1-1.5 days 🔄
  779 |    - Depends on Phase 1 completion ✅
  780 | 
  781 | ================
  782 | File: instructions/plan.md
  783 | ================
  784 | # Vibe-Coder MCP Server Implementation Plan
  785 | 
  786 | After examining the existing template MCP server and the provided documents, I'll outline a detailed implementation plan for creating the Vibe-Coder MCP server according to the PRD and Implementation documents.
  787 | 
  788 | ## Overview
  789 | 
  790 | The Vibe-Coder MCP server will guide casual coders through a structured development process using features exposed via the Model Context Protocol. It will transform the existing notes system into a comprehensive development workflow tool, helping LLMs organize code development through clarification workflows, documentation generation, and phased implementation.
  791 | 
  792 | ## Implementation Steps
  793 | 
  794 | ### Step 1: Server Configuration and Core Structure
  795 | 
  796 | I'll start by modifying the existing MCP server to align with the Vibe-Coder requirements:
  797 | 
  798 | 1. Update server metadata and capabilities
  799 | 2. Define core data structures for features, PRDs, and implementation plans
  800 | 3. Create in-memory storage for projects and their phases
  801 | 
  802 | ```typescript
  803 | // Core data types
  804 | type Feature = {
  805 |   id: string;
  806 |   name: string;
  807 |   description: string;
  808 |   clarificationResponses: ClarificationResponse[];
  809 |   prdDoc?: string;
  810 |   implDoc?: string;
  811 |   phases: Phase[];
  812 | };
  813 | 
  814 | type ClarificationResponse = {
  815 |   question: string;
  816 |   answer: string;
  817 | };
  818 | 
  819 | type Phase = {
  820 |   id: string;
  821 |   name: string;
  822 |   description: string;
  823 |   tasks: Task[];
  824 |   status: "pending" | "in_progress" | "completed" | "reviewed";
  825 | };
  826 | 
  827 | type Task = {
  828 |   description: string;
  829 |   completed: boolean;
  830 | };
  831 | 
  832 | // In-memory storage
  833 | const features: { [id: string]: Feature } = {};
  834 | ```
  835 | 
  836 | ### Step 2: Feature Clarification Implementation
  837 | 
  838 | The clarification module will use MCP tools to engage users in iterative questioning:
  839 | 
  840 | 1. Create a tool to initiate feature clarification
  841 | 2. Implement a tool to receive clarification responses
  842 | 3. Create a resource to retrieve clarification status
  843 | 
  844 | ```typescript
  845 | // Tool for initiating clarification
  846 | server.setRequestHandler(CallToolRequestSchema, async (request) => {
  847 |   if (request.params.name === "start_feature_clarification") {
  848 |     const featureName = String(request.params.arguments?.featureName || "");
  849 |     const featureId = generateId();
  850 |     
  851 |     features[featureId] = {
  852 |       id: featureId,
  853 |       name: featureName,
  854 |       description: String(request.params.arguments?.initialDescription || ""),
  855 |       clarificationResponses: [],
  856 |       phases: []
  857 |     };
  858 |     
  859 |     // Return first clarification question
  860 |     return {
  861 |       content: [{
  862 |         type: "text",
  863 |         text: `Feature ID: ${featureId}\n\nLet's clarify your feature request. What specific problem does this feature solve?`
  864 |       }]
  865 |     };
  866 |   }
  867 | 
  868 |   // Handle other tools...
  869 | });
  870 | ```
  871 | 
  872 | ### Step 3: PRD and Implementation Plan Generation
  873 | 
  874 | Implement tools to generate documentation based on clarification responses:
  875 | 
  876 | 1. Create a tool to generate the PRD document
  877 | 2. Implement a tool to create the implementation plan
  878 | 3. Add resources to access these documents
  879 | 
  880 | ```typescript
  881 | // Tool for generating PRD
  882 | server.setRequestHandler(CallToolRequestSchema, async (request) => {
  883 |   if (request.params.name === "generate_prd") {
  884 |     const featureId = String(request.params.arguments?.featureId);
  885 |     const feature = features[featureId];
  886 |     
  887 |     if (!feature) {
  888 |       throw new Error("Feature not found");
  889 |     }
  890 |     
  891 |     // Generate PRD content based on clarification responses
  892 |     const prdContent = generatePRD(feature);
  893 |     feature.prdDoc = prdContent;
  894 |     
  895 |     return {
  896 |       content: [{
  897 |         type: "text",
  898 |         text: `PRD generated successfully for ${feature.name}. You can view it using the "feature_prd" resource.`
  899 |       }]
  900 |     };
  901 |   }
  902 |   
  903 |   // Similar implementation for implementation plan generation...
  904 | });
  905 | ```
  906 | 
  907 | ### Step 4: Phase Management Implementation
  908 | 
  909 | Create tools to manage development phases:
  910 | 
  911 | 1. Implement a tool to create phases
  912 | 2. Add a tool to update phase status
  913 | 3. Create resources to view phase details
  914 | 
  915 | ```typescript
  916 | // Tool for creating a new phase
  917 | server.setRequestHandler(CallToolRequestSchema, async (request) => {
  918 |   if (request.params.name === "create_phase") {
  919 |     const featureId = String(request.params.arguments?.featureId);
  920 |     const phaseName = String(request.params.arguments?.name);
  921 |     const phaseDescription = String(request.params.arguments?.description);
  922 |     const tasks = JSON.parse(String(request.params.arguments?.tasks || "[]"));
  923 |     
  924 |     const feature = features[featureId];
  925 |     if (!feature) {
  926 |       throw new Error("Feature not found");
  927 |     }
  928 |     
  929 |     const phaseId = generateId();
  930 |     feature.phases.push({
  931 |       id: phaseId,
  932 |       name: phaseName,
  933 |       description: phaseDescription,
  934 |       tasks: tasks.map((task: string) => ({ description: task, completed: false })),
  935 |       status: "pending"
  936 |     });
  937 |     
  938 |     return {
  939 |       content: [{
  940 |         type: "text",
  941 |         text: `Phase "${phaseName}" created with ID: ${phaseId}`
  942 |       }]
  943 |     };
  944 |   }
  945 |   
  946 |   // Handle other tools...
  947 | });
  948 | ```
  949 | 
  950 | ### Step 5: Resource Implementation
  951 | 
  952 | Implement resources to retrieve feature data, PRDs, and implementation plans:
  953 | 
  954 | 1. Create resources for listing all features
  955 | 2. Add resources for accessing feature details
  956 | 3. Implement resources for retrieving PRDs and implementation plans
  957 | 
  958 | ```typescript
  959 | // Handler for listing available features as resources
  960 | server.setRequestHandler(ListResourcesRequestSchema, async () => {
  961 |   return {
  962 |     resources: [
  963 |       {
  964 |         uri: "features://list",
  965 |         mimeType: "text/plain",
  966 |         name: "Features List",
  967 |         description: "Lists all features being developed"
  968 |       },
  969 |       ...Object.values(features).flatMap(feature => [
  970 |         {
  971 |           uri: `feature://${feature.id}`,
  972 |           mimeType: "text/plain", 
  973 |           name: feature.name,
  974 |           description: `Details about feature: ${feature.name}`
  975 |         },
  976 |         {
  977 |           uri: `feature://${feature.id}/prd`,
  978 |           mimeType: "text/markdown",
  979 |           name: `${feature.name} PRD`,
  980 |           description: `PRD document for feature: ${feature.name}`
  981 |         },
  982 |         {
  983 |           uri: `feature://${feature.id}/implementation`,
  984 |           mimeType: "text/markdown",
  985 |           name: `${feature.name} Implementation Plan`,
  986 |           description: `Implementation plan for feature: ${feature.name}`
  987 |         }
  988 |       ])
  989 |     ]
  990 |   };
  991 | });
  992 | 
  993 | // Handler for reading feature resources
  994 | server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
  995 |   const url = new URL(request.params.uri);
  996 |   
  997 |   // Handle various resource types...
  998 |   if (url.protocol === "features:") {
  999 |     if (url.pathname === "/list") {
 1000 |       return {
 1001 |         contents: [{
 1002 |           uri: request.params.uri,
 1003 |           mimeType: "text/plain",
 1004 |           text: Object.values(features).map(f => `${f.id}: ${f.name}`).join("\n")
 1005 |         }]
 1006 |       };
 1007 |     }
 1008 |   }
 1009 |   
 1010 |   if (url.protocol === "feature:") {
 1011 |     const parts = url.pathname.split('/').filter(Boolean);
 1012 |     const featureId = parts[0];
 1013 |     const feature = features[featureId];
 1014 |     
 1015 |     if (!feature) {
 1016 |       throw new Error(`Feature ${featureId} not found`);
 1017 |     }
 1018 |     
 1019 |     if (parts.length === 1) {
 1020 |       // Return feature details
 1021 |       return {
 1022 |         contents: [{
 1023 |           uri: request.params.uri,
 1024 |           mimeType: "text/plain",
 1025 |           text: formatFeatureDetails(feature)
 1026 |         }]
 1027 |       };
 1028 |     }
 1029 |     
 1030 |     if (parts[1] === "prd") {
 1031 |       return {
 1032 |         contents: [{
 1033 |           uri: request.params.uri,
 1034 |           mimeType: "text/markdown",
 1035 |           text: feature.prdDoc || "PRD not yet generated"
 1036 |         }]
 1037 |       };
 1038 |     }
 1039 |     
 1040 |     // Handle other resource types...
 1041 |   }
 1042 |   
 1043 |   throw new Error("Resource not found");
 1044 | });
 1045 | ```
 1046 | 
 1047 | ### Step 6: Tool Implementation
 1048 | 
 1049 | Expose the main tools for interacting with the Vibe-Coder MCP server:
 1050 | 
 1051 | ```typescript
 1052 | server.setRequestHandler(ListToolsRequestSchema, async () => {
 1053 |   return {
 1054 |     tools: [
 1055 |       {
 1056 |         name: "start_feature_clarification",
 1057 |         description: "Start the clarification process for a new feature",
 1058 |         inputSchema: {
 1059 |           type: "object",
 1060 |           properties: {
 1061 |             featureName: {
 1062 |               type: "string",
 1063 |               description: "Name of the feature"
 1064 |             },
 1065 |             initialDescription: {
 1066 |               type: "string",
 1067 |               description: "Initial description of the feature"
 1068 |             }
 1069 |           },
 1070 |           required: ["featureName"]
 1071 |         }
 1072 |       },
 1073 |       {
 1074 |         name: "provide_clarification",
 1075 |         description: "Provide answer to a clarification question",
 1076 |         inputSchema: {
 1077 |           type: "object",
 1078 |           properties: {
 1079 |             featureId: {
 1080 |               type: "string",
 1081 |               description: "ID of the feature"
 1082 |             },
 1083 |             question: {
 1084 |               type: "string",
 1085 |               description: "Clarification question"
 1086 |             },
 1087 |             answer: {
 1088 |               type: "string",
 1089 |               description: "Answer to the clarification question"
 1090 |             }
 1091 |           },
 1092 |           required: ["featureId", "question", "answer"]
 1093 |         }
 1094 |       },
 1095 |       {
 1096 |         name: "generate_prd",
 1097 |         description: "Generate a PRD document based on clarification responses",
 1098 |         inputSchema: {
 1099 |           type: "object",
 1100 |           properties: {
 1101 |             featureId: {
 1102 |               type: "string",
 1103 |               description: "ID of the feature"
 1104 |             }
 1105 |           },
 1106 |           required: ["featureId"]
 1107 |         }
 1108 |       },
 1109 |       {
 1110 |         name: "generate_implementation_plan",
 1111 |         description: "Generate an implementation plan document",
 1112 |         inputSchema: {
 1113 |           type: "object",
 1114 |           properties: {
 1115 |             featureId: {
 1116 |               type: "string",
 1117 |               description: "ID of the feature"
 1118 |             }
 1119 |           },
 1120 |           required: ["featureId"]
 1121 |         }
 1122 |       },
 1123 |       {
 1124 |         name: "create_phase",
 1125 |         description: "Create a new implementation phase",
 1126 |         inputSchema: {
 1127 |           type: "object",
 1128 |           properties: {
 1129 |             featureId: {
 1130 |               type: "string",
 1131 |               description: "ID of the feature"
 1132 |             },
 1133 |             name: {
 1134 |               type: "string",
 1135 |               description: "Name of the phase"
 1136 |             },
 1137 |             description: {
 1138 |               type: "string",
 1139 |               description: "Description of the phase"
 1140 |             },
 1141 |             tasks: {
 1142 |               type: "string",
 1143 |               description: "JSON array of task descriptions"
 1144 |             }
 1145 |           },
 1146 |           required: ["featureId", "name", "description"]
 1147 |         }
 1148 |       },
 1149 |       {
 1150 |         name: "update_phase_status",
 1151 |         description: "Update the status of a phase",
 1152 |         inputSchema: {
 1153 |           type: "object",
 1154 |           properties: {
 1155 |             featureId: {
 1156 |               type: "string",
 1157 |               description: "ID of the feature"
 1158 |             },
 1159 |             phaseId: {
 1160 |               type: "string",
 1161 |               description: "ID of the phase"
 1162 |             },
 1163 |             status: {
 1164 |               type: "string",
 1165 |               description: "New status (pending, in_progress, completed, reviewed)"
 1166 |             }
 1167 |           },
 1168 |           required: ["featureId", "phaseId", "status"]
 1169 |         }
 1170 |       },
 1171 |       {
 1172 |         name: "update_task_status",
 1173 |         description: "Mark a task as completed or not completed",
 1174 |         inputSchema: {
 1175 |           type: "object",
 1176 |           properties: {
 1177 |             featureId: {
 1178 |               type: "string", 
 1179 |               description: "ID of the feature"
 1180 |             },
 1181 |             phaseId: {
 1182 |               type: "string",
 1183 |               description: "ID of the phase"
 1184 |             },
 1185 |             taskIndex: {
 1186 |               type: "number",
 1187 |               description: "Index of the task"
 1188 |             },
 1189 |             completed: {
 1190 |               type: "boolean",
 1191 |               description: "Whether the task is completed"
 1192 |             }
 1193 |           },
 1194 |           required: ["featureId", "phaseId", "taskIndex", "completed"]
 1195 |         }
 1196 |       }
 1197 |     ]
 1198 |   };
 1199 | });
 1200 | ```
 1201 | 
 1202 | ### Step 7: Prompt Implementation
 1203 | 
 1204 | Create prompts to guide users through the development workflow:
 1205 | 
 1206 | ```typescript
 1207 | server.setRequestHandler(ListPromptsRequestSchema, async () => {
 1208 |   return {
 1209 |     prompts: [
 1210 |       {
 1211 |         name: "clarify_feature",
 1212 |         description: "Guide to clarify a feature request through questioning"
 1213 |       },
 1214 |       {
 1215 |         name: "generate_prd_template",
 1216 |         description: "Guide to generate a PRD document from clarifications"
 1217 |       },
 1218 |       {
 1219 |         name: "phase_implementation_guide",
 1220 |         description: "Guide for implementing a development phase"
 1221 |       }
 1222 |     ]
 1223 |   };
 1224 | });
 1225 | 
 1226 | server.setRequestHandler(GetPromptRequestSchema, async (request) => {
 1227 |   if (request.params.name === "clarify_feature") {
 1228 |     return {
 1229 |       messages: [
 1230 |         {
 1231 |           role: "user",
 1232 |           content: {
 1233 |             type: "text",
 1234 |             text: "Help me clarify this feature request by asking questions about:"
 1235 |           }
 1236 |         },
 1237 |         {
 1238 |           role: "user",
 1239 |           content: {
 1240 |             type: "text",
 1241 |             text: "1. The specific problem it solves\n2. The target users\n3. Key requirements\n4. Success criteria\n5. Technical constraints\n\nAsk one question at a time, analyze the response, then proceed to the next most relevant question."
 1242 |           }
 1243 |         }
 1244 |       ]
 1245 |     };
 1246 |   }
 1247 |   
 1248 |   // Handle other prompts...
 1249 | });
 1250 | ```
 1251 | 
 1252 | ## Helper Functions to Implement
 1253 | 
 1254 | Here are the core helper functions needed for the implementation:
 1255 | 
 1256 | ```typescript
 1257 | // Generate unique IDs
 1258 | function generateId(): string {
 1259 |   return Math.random().toString(36).substring(2, 15);
 1260 | }
 1261 | 
 1262 | // Format feature details for display
 1263 | function formatFeatureDetails(feature: Feature): string {
 1264 |   return `
 1265 | Feature: ${feature.name}
 1266 | ID: ${feature.id}
 1267 | Description: ${feature.description}
 1268 | 
 1269 | Clarification Responses:
 1270 | ${feature.clarificationResponses.map(cr => `Q: ${cr.question}\nA: ${cr.answer}`).join('\n\n')}
 1271 | 
 1272 | Phases (${feature.phases.length}):
 1273 | ${feature.phases.map(p => `- ${p.name} (${p.status}): ${p.tasks.filter(t => t.completed).length}/${p.tasks.length} tasks completed`).join('\n')}
 1274 | `;
 1275 | }
 1276 | 
 1277 | // Generate PRD document
 1278 | function generatePRD(feature: Feature): string {
 1279 |   const clarifications = feature.clarificationResponses;
 1280 |   
 1281 |   return `# ${feature.name} PRD
 1282 | 
 1283 | ## 1. Introduction
 1284 | 
 1285 | ${feature.description}
 1286 | 
 1287 | ## 2. Feature Objectives
 1288 | 
 1289 | ${extractObjectivesFromClarifications(clarifications)}
 1290 | 
 1291 | ## 3. Scope and Requirements
 1292 | 
 1293 | ${extractRequirementsFromClarifications(clarifications)}
 1294 | 
 1295 | ## 4. High-Level Implementation Overview
 1296 | 
 1297 | To be determined based on the implementation plan.
 1298 | 
 1299 | ## 5. Feedback and Iteration Process
 1300 | 
 1301 | This PRD will be updated as the implementation progresses and feedback is received.
 1302 | `;
 1303 | }
 1304 | 
 1305 | // Generate implementation plan
 1306 | function generateImplementationPlan(feature: Feature): string {
 1307 |   // Similar to PRD generation, but creating an implementation plan
 1308 |   // ...
 1309 | }
 1310 | 
 1311 | // Extract objectives from clarification responses
 1312 | function extractObjectivesFromClarifications(responses: ClarificationResponse[]): string {
 1313 |   // Logic to extract objectives based on responses to clarification questions
 1314 |   // ...
 1315 | }
 1316 | 
 1317 | // Extract requirements from clarification responses
 1318 | function extractRequirementsFromClarifications(responses: ClarificationResponse[]): string {
 1319 |   // Logic to extract requirements based on responses to clarification questions
 1320 |   // ...
 1321 | }
 1322 | ```
 1323 | 
 1324 | ## File Structure
 1325 | 
 1326 | The implementation will be organized as follows:
 1327 | 
 1328 | ```
 1329 | src/
 1330 |   ├── index.ts               # Main server entry point
 1331 |   ├── types.ts               # Type definitions
 1332 |   ├── storage.ts             # Feature storage management
 1333 |   ├── clarification.ts       # Clarification workflow logic
 1334 |   ├── documentation.ts       # PRD and implementation plan generation
 1335 |   ├── phases.ts              # Phase and task management
 1336 |   ├── utils.ts               # Helper utilities
 1337 |   ├── handlers/              # MCP request handlers
 1338 |   │   ├── resources.ts       # Resource request handlers
 1339 |   │   ├── tools.ts           # Tool request handlers
 1340 |   │   └── prompts.ts         # Prompt request handlers
 1341 |   └── templates/             # Documentation templates
 1342 |       ├── prd-template.md    # PRD document template
 1343 |       └── impl-template.md   # Implementation plan template
 1344 | ```
 1345 | 
 1346 | ## Implementation Timeline
 1347 | 
 1348 | 1. **Week 1**: Set up core server structure and data models
 1349 | 2. **Week 2**: Implement feature clarification workflow
 1350 | 3. **Week 3**: Build PRD and implementation plan generation
 1351 | 4. **Week 4**: Develop phase management functionality
 1352 | 5. **Week 5**: Complete resources and refinements
 1353 | 6. **Week 6**: Testing and documentation
 1354 | 
 1355 | ## Next Steps
 1356 | 
 1357 | 1. Start by modifying the existing server to match the Vibe-Coder requirements
 1358 | 2. Implement the core data structures and storage
 1359 | 3. Build feature clarification tools and resources
 1360 | 4. Add document generation capabilities
 1361 | 5. Implement phase management tools
 1362 | 6. Complete integration with MCP
 1363 | 
 1364 | ================
 1365 | File: instructions/PRD.md
 1366 | ================
 1367 | # Vibe-Coder MCP Server PRD
 1368 | 
 1369 | ## 1. Introduction
 1370 | 
 1371 | The Vibe-Coder MCP Server is designed to help casual, LLM-based coders build new features in an organized, clean, and safe manner. By leveraging the Model Context Protocol (MCP), this server guides users through a structured process—from clarifying feature requests to implementing them in discrete, verifiable phases. This document defines the product requirements and lays the groundwork for the detailed implementation plan.
 1372 | 
 1373 | ## 2. Feature Objectives
 1374 | 
 1375 | - **Assist LLM-based Coders:** Enable casual developers (vibe coders) to request and build features efficiently using an LLM-driven workflow.
 1376 | - **Structured Development:** Organize the feature creation process into clearly defined stages, ensuring each phase is documented, reviewed, and implemented according to best practices.
 1377 | - **Clean and Safe Code:** Enforce code quality standards, safe implementation practices, and thorough documentation throughout the development cycle.
 1378 | - **Iterative Clarification:** Engage users in rounds of questions to continuously refine and narrow down the feature requirements.
 1379 | 
 1380 | ## 3. Scope and Requirements
 1381 | 
 1382 | ### 3.1 Feature Request Clarification
 1383 | - **Iterative Engagement:**  
 1384 |   - The system will prompt users with follow-up questions to clarify the exact goals and nuances of the requested feature.
 1385 |   - User responses will be recorded and used to refine the feature’s scope.
 1386 | 
 1387 | ### 3.2 PRD Documentation
 1388 | - **Concise PRD Drafting:**  
 1389 |   - Develop a narrow and specific PRD that captures:
 1390 |     - **Feature Objectives:** A clear description of what the feature should achieve.
 1391 |     - **Detailed Requirements:** Specific, actionable requirements and constraints.
 1392 |     - **Documentation References:** Links or references to relevant code formats, style guides, and best practices.
 1393 | - **File Organization:**  
 1394 |   - Save the PRD as a Markdown file using the naming convention:  
 1395 |     `StepNumber_FeatureName_PRD.md`  
 1396 |     *(Example: “01_VibeCoder_PRD.md”)*
 1397 | 
 1398 | ### 3.3 Implementation Specification
 1399 | - **Phased Breakdown:**  
 1400 |   - Divide the feature’s implementation into discrete phases, where each phase addresses a single focused task.
 1401 | - **Checklists and Standards:**  
 1402 |   - For each phase, include a checklist detailing:
 1403 |     - Task requirements
 1404 |     - Code style and practices that must be adhered to
 1405 | - **Separate Documentation:**  
 1406 |   - Save the implementation plan in its own Markdown file, following the naming convention:  
 1407 |     `StepNumber_FeatureName_Implementation.md`
 1408 | 
 1409 | ## 4. High-Level Implementation Overview
 1410 | 
 1411 | ### 4.1 Development Workflow and Branching Strategy
 1412 | - **Feature Branch:**  
 1413 |   - Begin each new feature on a dedicated branch.
 1414 | - **Phase Branches:**  
 1415 |   - For every discrete phase within a feature, create a new branch off the feature branch.
 1416 | - **Commit and Code Review Process:**  
 1417 |   - After completing each phase:
 1418 |     - Create detailed git commits capturing all changes.
 1419 |     - Request a targeted code review that includes the PRD, the phase-specific implementation plan, and the relevant code changes.
 1420 |     - Merge the phase branch back into the feature branch (retain phase branches for history).
 1421 | 
 1422 | ### 4.2 Finalization Process
 1423 | - **Project Summary:**  
 1424 |   - Upon feature completion, update the project README with a summary of the new functionality.
 1425 | - **Feature-Specific README:**  
 1426 |   - Create a dedicated README that details:
 1427 |     - The new feature’s functionality
 1428 |     - How to use the feature
 1429 |     - The adherence to the documented practices and checklists
 1430 | - **Final Code Review:**  
 1431 |   - Conduct a comprehensive code review covering all documentation and code, ensuring only the relevant portions are evaluated.
 1432 | 
 1433 | ## 5. Structuring the MCP for LLM Compliance
 1434 | 
 1435 | To ensure the LLM follows the outlined instructions accurately, the following practices are essential:
 1436 | 
 1437 | - **Clear Hierarchical Sections:**  
 1438 |   - Use distinct headings and subheadings for each major section (e.g., Introduction, Objectives, Scope, etc.).
 1439 | - **Step-by-Step Breakdown:**  
 1440 |   - Organize tasks in numbered steps with clear, actionable directives (e.g., “Draft the PRD,” “Create phase-specific branches”).
 1441 | - **Consistent Naming Conventions:**  
 1442 |   - Specify precise file and branch naming formats to eliminate ambiguity.
 1443 | - **Imperative Language:**  
 1444 |   - Use direct commands (e.g., “Create,” “Define,” “Save,” “Merge”) to ensure clarity.
 1445 | - **Checklists and Examples:**  
 1446 |   - Provide concrete examples or templates for PRD sections, implementation plans, and commit messages to serve as models.
 1447 | - **Feedback Loops:**  
 1448 |   - Include instructions to ask clarifying questions if any step is ambiguous.
 1449 | - **Documentation Focus:**  
 1450 |   - Emphasize thorough documentation of every phase with clear checklists and version control histories.
 1451 | 
 1452 | ## 6. Feedback and Iteration Process
 1453 | 
 1454 | - **User Feedback Integration:**  
 1455 |   - Regularly incorporate user feedback to refine feature objectives and requirements.
 1456 | - **Iterative Updates:**  
 1457 |   - Update both the PRD and the implementation plan as new details emerge during the development process.
 1458 | - **Review and Approval:**  
 1459 |   - Ensure that each phase is reviewed and approved before moving to subsequent phases.
 1460 | 
 1461 | ## 7. Appendix
 1462 | 
 1463 | ### 7.1 File Naming Conventions
 1464 | - **PRD File:** `StepNumber_FeatureName_PRD.md`  
 1465 |   *(Example: “01_VibeCoder_PRD.md”)*
 1466 | - **Implementation Plan File:** `StepNumber_FeatureName_Implementation.md`
 1467 | 
 1468 | ### 7.2 Example Checklists and Templates
 1469 | - **Feature Request Checklist:**  
 1470 |   - [ ] Define feature objective  
 1471 |   - [ ] Clarify user requirements through iterative questions  
 1472 |   - [ ] Record user responses for scope refinement  
 1473 | - **Phase Implementation Checklist:**  
 1474 |   - [ ] Define phase-specific tasks  
 1475 |   - [ ] Outline required code standards and practices  
 1476 |   - [ ] Document progress with commit messages  
 1477 |   - [ ] Request targeted code review  
 1478 |   - [ ] Merge phase branch into feature branch after review
 1479 | 
 1480 | ================
 1481 | File: instructions/solidity_tic_tac_toe_project.md
 1482 | ================
 1483 | # Solidity Tic Tac Toe Project
 1484 | 
 1485 | **Feature ID:** feature-hy5l98td
 1486 | 
 1487 | ## Clarification Responses
 1488 | 
 1489 | ### What specific problem does this feature solve?
 1490 | This feature solves the problem of creating verifiable, tamper-proof gaming experiences on blockchain. It demonstrates how traditional games can be implemented in a decentralized manner where the game state and rules are enforced by smart contracts rather than a central server, ensuring fair play and transparent outcomes.
 1491 | 
 1492 | ### Who are the target users for this feature?
 1493 | The target users are: 
 1494 | 1) Blockchain enthusiasts who want to experience decentralized gaming
 1495 | 2) Ethereum developers learning how to implement game logic in smart contracts
 1496 | 3) Educational platforms teaching blockchain concepts through familiar games
 1497 | 4) Players interested in crypto-gaming who want to try simple blockchain games with potential for token rewards
 1498 | 
 1499 | ### What are the key requirements for this feature?
 1500 | Key requirements include: 
 1501 | 1) A Solidity smart contract that implements the complete Tic Tac Toe game logic
 1502 | 2) Functions for player registration and turn management
 1503 | 3) Win condition detection and game state verification
 1504 | 4) Prevention of illegal moves and proper handling of drawn games
 1505 | 5) Option for players to wager ETH on game outcomes
 1506 | 6) Events that can be used by a frontend to track game progress
 1507 | 7) Gas-efficient implementation to minimize transaction costs
 1508 | 
 1509 | ### What are the technical constraints or considerations?
 1510 | Technical constraints include: 
 1511 | 1) Gas optimization is critical - each move costs ETH to execute
 1512 | 2) The contract must be compatible with Solidity 0.8.x and deployable to Ethereum and compatible chains like Polygon
 1513 | 3) State management must be efficient as blockchain storage is expensive
 1514 | 4) Proper access control is needed to ensure only valid players can make moves in their own games
 1515 | 5) Time constraints should be considered to prevent abandoned games
 1516 | 6) Input validation is crucial to prevent exploits or illegal game states
 1517 | 7) No external dependencies should be required beyond standard Solidity libraries
 1518 | 
 1519 | ### How will we measure the success of this feature?
 1520 | Success will be measured by: 
 1521 | 1) Successful deployment of the contract to a testnet with verified gameplay
 1522 | 2) Completion of full games without errors or invalid states
 1523 | 3) Gas usage below 200,000 gas per move
 1524 | 4) Proper detection of all win conditions and draws
 1525 | 5) Correct handling of wagers and payouts
 1526 | 6) Successful integration with a basic web frontend for demonstration
 1527 | 7) Security audit passing without critical vulnerabilities
 1528 | 8) Documentation that allows developers to understand and interact with the contract
 1529 | 
 1530 | ### Are there any dependencies on other features or systems?
 1531 | Dependencies include: 
 1532 | 1) Ethereum or compatible blockchain network for deployment
 1533 | 2) Solidity compiler version 0.8.x
 1534 | 3) Hardhat or Truffle for development, testing and deployment
 1535 | 4) Ethers.js or Web3.js for frontend integration
 1536 | 5) MetaMask or similar Web3 provider for user interaction
 1537 | 6) A basic frontend application (HTML/JS/CSS) for user interface, though this could be developed separately
 1538 | 7) OpenZeppelin contracts for secure implementation patterns (optional)
 1539 | 
 1540 | ### What are the potential risks or challenges in implementing this feature?
 1541 | The potential risks and challenges include: 
 1542 | 1) High gas costs making gameplay expensive if not optimized
 1543 | 2) Smart contract security vulnerabilities like reentrancy attacks or integer overflows
 1544 | 3) Poor user experience due to blockchain transaction delays
 1545 | 4) Abandoned games if players stop participating
 1546 | 5) Complexity in handling edge cases like ties or unexpected termination
 1547 | 6) Difficulties in upgrading the contract if bugs are found since blockchain code is immutable
 1548 | 7) Ensuring fairness in the game mechanics while maintaining decentralization
 1549 | 8) Testing challenges due to the distributed nature of blockchain applications
 1550 | 
 1551 | ## Development Phases
 1552 | 
 1553 | ### Phase 1: Smart Contract Development
 1554 | **Status**: In Progress
 1555 | **Description**: Develop the core Solidity smart contract for the Tic Tac Toe game, including game logic, state management, and event emission.
 1556 | 
 1557 | **Tasks**:
 1558 | - Set up Hardhat development environment with Solidity 0.8.x
 1559 | - Implement game board representation and state management
 1560 | - Implement player registration and game creation functionality
 1561 | - Implement move validation and game state updates
 1562 | - Implement win condition detection and game completion logic
 1563 | 
 1564 | ### Phase 2: Testing and Optimization
 1565 | **Description**: Write test cases, optimize gas usage, and ensure security of the Tic Tac Toe contract.
 1566 | 
 1567 | **Tasks**:
 1568 | - Write unit tests for all game functionality
 1569 | - Perform gas optimization for core game functions
 1570 | - Conduct security review and implement safeguards
 1571 | 
 1572 | ### Phase 3: Deployment and Documentation
 1573 | **Description**: Deploy the contract to testnets and create comprehensive documentation for developers and users.
 1574 | 
 1575 | **Tasks**:
 1576 | - Deploy contract to Ethereum testnet (Goerli/Sepolia)
 1577 | - Create technical documentation with API references
 1578 | - Create a demo frontend for interacting with the contract
 1579 | 
 1580 | ## Product Requirements Document
 1581 | 
 1582 | ### 1. Introduction
 1583 | 
 1584 | #### 1.1 Purpose
 1585 | This document outlines the requirements and specifications for a decentralized Tic Tac Toe game implemented as a Solidity smart contract on the Ethereum blockchain. The goal is to create a fully functional, gas-efficient, and secure implementation that demonstrates how traditional games can be implemented in a trustless, decentralized environment.
 1586 | 
 1587 | #### 1.2 Scope
 1588 | The scope of this product includes the smart contract implementation of Tic Tac Toe, including game creation, player management, game logic, win condition detection, and wagering functionality. A basic web frontend for interacting with the contract will be developed as part of the demonstration but is not the primary focus of this PRD.
 1589 | 
 1590 | #### 1.3 Background
 1591 | Blockchain games represent a growing segment of the web3 ecosystem, offering new possibilities for transparent and verifiable gameplay. Tic Tac Toe, as a simple yet widely understood game, provides an excellent introduction to smart contract gaming concepts while being straightforward enough to implement efficiently on-chain.
 1592 | 
 1593 | ### 2. Product Overview
 1594 | 
 1595 | #### 2.1 Product Description
 1596 | A decentralized Tic Tac Toe game built on Ethereum that allows two players to compete against each other with all game actions and state changes recorded on the blockchain. Players can create games, join existing games, make moves, and potentially wager ETH on the outcome.
 1597 | 
 1598 | #### 2.2 Target Users
 1599 | - Blockchain enthusiasts interested in decentralized applications
 1600 | - Ethereum developers learning smart contract development
 1601 | - Educational platforms teaching blockchain concepts
 1602 | - Casual players interested in crypto gaming experiences
 1603 | 
 1604 | ### 3. Functional Requirements
 1605 | 
 1606 | #### 3.1 Game Creation and Setup
 1607 | - Users must be able to create a new game, becoming player 1 (X)
 1608 | - Users must be able to join an existing open game as player 2 (O)
 1609 | - Game creators must be able to specify whether ETH wagering is enabled
 1610 | - If wagering is enabled, both players must contribute the same amount of ETH to participate
 1611 | 
 1612 | #### 3.2 Gameplay Mechanics
 1613 | - The game board must be represented as a 3x3 grid
 1614 | - Players must take turns making moves, with player 1 (X) always going first
 1615 | - The contract must validate moves to ensure they are made:
 1616 |   - By the correct player
 1617 |   - On a valid, empty position on the board
 1618 |   - During an active game
 1619 | - The contract must prevent players from making moves when it's not their turn
 1620 | - The contract must update and store the game state after each valid move
 1621 | 
 1622 | #### 3.3 Win Conditions and Game Completion
 1623 | - The contract must detect win conditions: 3 in a row horizontally, vertically, or diagonally
 1624 | - The contract must detect draw conditions when all positions are filled with no winner
 1625 | - When a game is completed, the contract must:
 1626 |   - Record the winner (or draw)
 1627 |   - Prevent further moves
 1628 |   - Distribute any wagered ETH to the winner (or refund in case of a draw)
 1629 | 
 1630 | #### 3.4 Event Emission
 1631 | - The contract must emit events for:
 1632 |   - Game creation
 1633 |   - Player joining a game
 1634 |   - Each valid move made
 1635 |   - Game completion (win/draw)
 1636 |   - ETH distribution if wagering is enabled
 1637 | 
 1638 | ### 4. Non-Functional Requirements
 1639 | 
 1640 | #### 4.1 Performance and Optimization
 1641 | - Gas usage for moves should be below 200,000 gas
 1642 | - The contract should minimize on-chain storage to reduce gas costs
 1643 | - The game logic should be optimized for minimal computational complexity
 1644 | 
 1645 | #### 4.2 Security
 1646 | - The contract must implement proper access controls
 1647 | - Input validation must be comprehensive to prevent unexpected game states
 1648 | - The contract should be resistant to common smart contract vulnerabilities
 1649 | - The contract must handle ETH transfers securely if wagering is enabled
 1650 | 
 1651 | #### 4.3 Compatibility
 1652 | - The contract must be compatible with Solidity 0.8.x
 1653 | - The contract must be deployable to Ethereum mainnet and testnets
 1654 | - The contract should work with standard Web3 providers like MetaMask
 1655 | 
 1656 | ### 5. Technical Specifications
 1657 | 
 1658 | #### 5.1 Smart Contract Architecture
 1659 | - `TicTacToe.sol`: Main contract implementing the game logic
 1660 | - Data structures:
 1661 |   - Game struct containing board state, player addresses, current turn, game status, and wager information
 1662 |   - Mapping from game ID to Game struct for multi-game support
 1663 | - Key functions:
 1664 |   - `createGame()`: Create a new game instance
 1665 |   - `joinGame(uint gameId)`: Join an existing game
 1666 |   - `makeMove(uint gameId, uint8 x, uint8 y)`: Make a move on the board
 1667 |   - `getGameState(uint gameId)`: Return the current state of a specific game
 1668 | 
 1669 | #### 5.2 Development Environment
 1670 | - Hardhat for development, testing, and deployment
 1671 | - Solidity 0.8.x as the smart contract language
 1672 | - Ethers.js for frontend integration
 1673 | - OpenZeppelin contracts for security patterns (optional)
 1674 | 
 1675 | ### 6. User Interface (Frontend)
 1676 | 
 1677 | While the frontend is not the primary focus, a basic web interface should be developed to demonstrate interaction with the smart contract:
 1678 | 
 1679 | #### 6.1 Key Frontend Features
 1680 | - Connect wallet functionality
 1681 | - Create new game / Join existing game options
 1682 | - Visual representation of the game board
 1683 | - Move selection interface
 1684 | - Game status display
 1685 | - Transaction status and confirmation
 1686 | 
 1687 | ### 7. Testing Strategy
 1688 | 
 1689 | #### 7.1 Unit Testing
 1690 | - Test all contract functions in isolation
 1691 | - Verify win condition logic covers all possible winning configurations
 1692 | - Test error conditions and invalid inputs
 1693 | 
 1694 | #### 7.2 Integration Testing
 1695 | - Test full game scenarios from creation to completion
 1696 | - Test wagering functionality if implemented
 1697 | - Verify correct event emission
 1698 | 
 1699 | #### 7.3 Security Testing
 1700 | - Review for common smart contract vulnerabilities
 1701 | - Test for correct access control enforcement
 1702 | - Verify proper handling of ETH transfers
 1703 | 
 1704 | ### 8. Milestones and Implementation Plan
 1705 | 
 1706 | The implementation will be organized into three main phases:
 1707 | 
 1708 | #### 8.1 Phase 1: Smart Contract Development
 1709 | - Set up development environment
 1710 | - Implement core game logic and state management
 1711 | - Build player registration and turn management
 1712 | - Create win condition detection
 1713 | 
 1714 | #### 8.2 Phase 2: Testing and Optimization
 1715 | - Develop comprehensive test suite
 1716 | - Optimize for gas efficiency
 1717 | - Conduct security review
 1718 | 
 1719 | #### 8.3 Phase 3: Deployment and Documentation
 1720 | - Deploy to Ethereum testnet
 1721 | - Create technical documentation
 1722 | - Develop demo frontend
 1723 | 
 1724 | ## Implementation Plan
 1725 | 
 1726 | ### 1. Environment Setup
 1727 | 
 1728 | #### 1.1 Development Environment
 1729 | - Set up a Hardhat project for Solidity development
 1730 | - Configure for Solidity version 0.8.17
 1731 | - Install necessary dependencies:
 1732 |   - `@openzeppelin/contracts` (optional, for security patterns)
 1733 |   - `@nomiclabs/hardhat-ethers` for testing
 1734 |   - `@nomiclabs/hardhat-waffle` for testing
 1735 | - Configure testing environment with Hardhat
 1736 | 
 1737 | #### 1.2 Project Structure
 1738 | ```
 1739 | /contracts
 1740 |   /TicTacToe.sol
 1741 | /test
 1742 |   /TicTacToe.test.js
 1743 | /scripts
 1744 |   /deploy.js
 1745 | /frontend (optional for demo)
 1746 |   /src
 1747 |     /components
 1748 |     /utils
 1749 | hardhat.config.js
 1750 | package.json
 1751 | README.md
 1752 | ```
 1753 | 
 1754 | ### 2. Smart Contract Development
 1755 | 
 1756 | #### 2.1 Contract Data Structures
 1757 | 
 1758 | Define the core data structures:
 1759 | 
 1760 | ```solidity
 1761 | // Game status enum
 1762 | enum GameStatus { OPEN, IN_PROGRESS, WINNER_X, WINNER_O, DRAW }
 1763 | 
 1764 | // Game struct to track game state
 1765 | struct Game {
 1766 |     address playerX;         // Player 1 (X)
 1767 |     address playerO;         // Player 2 (O)
 1768 |     address currentTurn;     // Whose turn it is
 1769 |     uint8[9] board;          // Board state (0=empty, 1=X, 2=O)
 1770 |     GameStatus status;       // Current game status
 1771 |     uint256 wagerAmount;     // ETH wagered (if any)
 1772 |     uint256 createdAt;       // Timestamp for game creation
 1773 | }
 1774 | 
 1775 | // Mapping to track all games
 1776 | mapping(uint256 => Game) public games;
 1777 | uint256 public gameCount;
 1778 | ```
 1779 | 
 1780 | #### 2.2 Core Game Functions
 1781 | 
 1782 | Implement these core functions:
 1783 | 
 1784 | 1. **Game Creation**
 1785 | ```solidity
 1786 | function createGame(bool withWager) external payable returns (uint256 gameId) {
 1787 |     // Input validation for wager
 1788 |     // Create new game with player X as msg.sender
 1789 |     // Set initial game state
 1790 |     // Emit GameCreated event
 1791 | }
 1792 | ```
 1793 | 
 1794 | 2. **Joining a Game**
 1795 | ```solidity
 1796 | function joinGame(uint256 gameId) external payable {
 1797 |     // Validate game exists and is open
 1798 |     // Validate wager amount if needed
 1799 |     // Set player O as msg.sender
 1800 |     // Update game status to IN_PROGRESS
 1801 |     // Emit PlayerJoined event
 1802 | }
 1803 | ```
 1804 | 
 1805 | 3. **Making a Move**
 1806 | ```solidity
 1807 | function makeMove(uint256 gameId, uint8 position) external {
 1808 |     // Validate game state and player turn
 1809 |     // Validate move is legal (position is in range and empty)
 1810 |     // Update board state
 1811 |     // Check for win conditions
 1812 |     // Update game status if game is complete
 1813 |     // Handle ETH distribution if game is complete and has wager
 1814 |     // Emit MoveExecuted event
 1815 | }
 1816 | ```
 1817 | 
 1818 | 4. **Game State Retrieval**
 1819 | ```solidity
 1820 | function getGameState(uint256 gameId) external view returns (
 1821 |     address playerX,
 1822 |     address playerO,
 1823 |     address currentTurn,
 1824 |     uint8[9] memory board,
 1825 |     GameStatus status
 1826 | ) {
 1827 |     // Return all relevant game state information
 1828 | }
 1829 | ```
 1830 | 
 1831 | #### 2.3 Win Condition Detection
 1832 | 
 1833 | Implement an efficient algorithm to check for wins:
 1834 | ```solidity
 1835 | function checkWinner(uint8[9] memory board) internal pure returns (bool hasWinner, uint8 winner) {
 1836 |     // Check rows, columns, and diagonals for 3 in a row
 1837 |     // Return winner (1 for X, 2 for O) if found
 1838 |     // Otherwise return no winner
 1839 | }
 1840 | ```
 1841 | 
 1842 | #### 2.4 ETH Handling
 1843 | 
 1844 | Handle wagering functionality:
 1845 | ```solidity
 1846 | function _distributeWinnings(Game storage game) internal {
 1847 |     // Send ETH to winner or refund in case of draw
 1848 |     // Handle potential transfer failures safely
 1849 | }
 1850 | ```
 1851 | 
 1852 | ### 3. Testing Strategy
 1853 | 
 1854 | #### 3.1 Unit Tests
 1855 | Write tests for:
 1856 | - Game creation with and without wager
 1857 | - Joining games
 1858 | - Making valid and invalid moves
 1859 | - Win detection for all winning positions
 1860 | - Draw detection
 1861 | - ETH distribution logic
 1862 | 
 1863 | #### 3.2 Gas Optimization
 1864 | - Use uint8 for board positions (0, 1, 2)
 1865 | - Optimize win condition checking
 1866 | - Minimize storage operations
 1867 | - Consider using bit manipulation for board state
 1868 | 
 1869 | ### 4. Deployment and Documentation
 1870 | 
 1871 | #### 4.1 Deployment Scripts
 1872 | Create scripts for:
 1873 | - Testnet deployment
 1874 | - Local testing deployment
 1875 | 
 1876 | #### 4.2 Documentation
 1877 | Document:
 1878 | - Contract functions and parameters
 1879 | - Game mechanics and flow
 1880 | - Integration guidelines for frontends
 1881 | - Examples of interaction using ethers.js
 1882 | 
 1883 | #### 4.3 Frontend Demo (Optional)
 1884 | If time permits, create a basic React frontend:
 1885 | - Wallet connection
 1886 | - Game creation interface
 1887 | - Game board visualization
 1888 | - Move submission
 1889 | 
 1890 | ### 5. Implementation Timeline
 1891 | 
 1892 | #### Week 1: Smart Contract Development
 1893 | - Day 1-2: Set up environment and implement data structures
 1894 | - Day 3-4: Implement core game functions
 1895 | - Day 5: Implement win condition detection and ETH handling
 1896 | 
 1897 | #### Week 2: Testing and Optimization
 1898 | - Day 1-2: Write comprehensive tests
 1899 | - Day 3-4: Gas optimization
 1900 | - Day 5: Security review
 1901 | 
 1902 | #### Week 3: Deployment and Documentation
 1903 | - Day 1-2: Create deployment scripts and deploy to testnet
 1904 | - Day 3-4: Write documentation
 1905 | - Day 5: (Optional) Create basic frontend demo
 1906 | 
 1907 | ================
 1908 | File: src/templates/impl-template.md
 1909 | ================
 1910 | # {{featureName}} Implementation Plan
 1911 | 
 1912 | ## Overview
 1913 | 
 1914 | {{featureDescription}}
 1915 | 
 1916 | ## Implementation Steps
 1917 | 
 1918 | {{#each phases}}
 1919 | ### Phase {{phaseNumber}}: {{phaseName}}
 1920 | 
 1921 | #### Objectives
 1922 | {{objectives}}
 1923 | 
 1924 | #### Tasks
 1925 | {{#each tasks}}
 1926 | - [ ] {{description}}
 1927 | {{/each}}
 1928 | 
 1929 | #### Code Style & Practices
 1930 | {{codeStyle}}
 1931 | 
 1932 | {{/each}}
 1933 | 
 1934 | ## File Structure
 1935 | 
 1936 | ```
 1937 | {{fileStructure}}
 1938 | ```
 1939 | 
 1940 | ## Implementation Timeline
 1941 | 
 1942 | {{#each phases}}
 1943 | {{phaseNumber}}. **{{phaseName}}**: {{timeEstimate}}
 1944 | {{/each}}
 1945 | 
 1946 | ## Next Steps
 1947 | 
 1948 | 1. {{nextStep1}}
 1949 | 2. {{nextStep2}}
 1950 | 3. {{nextStep3}}
 1951 | 4. {{nextStep4}}
 1952 | 5. {{nextStep5}}
 1953 | 
 1954 | ================
 1955 | File: src/templates/prd-template.md
 1956 | ================
 1957 | # {{featureName}} PRD
 1958 | 
 1959 | ## 1. Introduction
 1960 | 
 1961 | {{featureDescription}}
 1962 | 
 1963 | ## 2. Feature Objectives
 1964 | 
 1965 | {{objectives}}
 1966 | 
 1967 | ## 3. Scope and Requirements
 1968 | 
 1969 | ### 3.1 Feature Request Clarification
 1970 | {{requirements}}
 1971 | 
 1972 | ### 3.2 Technical Specifications
 1973 | {{technicalSpecs}}
 1974 | 
 1975 | ## 4. High-Level Implementation Overview
 1976 | 
 1977 | ### 4.1 Development Workflow and Branching Strategy
 1978 | - **Feature Branch:**  
 1979 |   - Begin implementation on a dedicated branch named `feature/{{featureNameSlug}}`.
 1980 | - **Phase Branches:**  
 1981 |   - For each phase, create a branch off the feature branch named `phase/{{featureNameSlug}}/{{phaseNumber}}-{{phaseName}}`.
 1982 | 
 1983 | ### 4.2 Implementation Phases
 1984 | {{implementationPhases}}
 1985 | 
 1986 | ## 5. Feedback and Iteration Process
 1987 | 
 1988 | - **User Feedback Integration:**  
 1989 |   - Regularly incorporate user feedback to refine feature objectives and requirements.
 1990 | - **Iterative Updates:**  
 1991 |   - Update both the PRD and the implementation plan as new details emerge during the development process.
 1992 | - **Review and Approval:**  
 1993 |   - Ensure that each phase is reviewed and approved before moving to subsequent phases.
 1994 | 
 1995 | ## 6. File Naming Conventions
 1996 | - **PRD File:** `{{stepNumber}}_{{featureName}}_PRD.md`
 1997 | - **Implementation Plan File:** `{{stepNumber}}_{{featureName}}_Implementation.md`
 1998 | 
 1999 | ================
 2000 | File: src/clarification.ts
 2001 | ================
 2002 | /**
 2003 |  * Feature clarification module for the Vibe-Coder MCP Server.
 2004 |  * This module handles the iterative questioning to clarify feature requests.
 2005 |  */
 2006 | import { Feature, ClarificationResponse } from './types.js';
 2007 | import { updateFeature, getFeature } from './storage.js';
 2008 | import { now } from './utils.js';
 2009 | 
 2010 | /**
 2011 |  * Default questions to ask during feature clarification
 2012 |  */
 2013 | export const DEFAULT_CLARIFICATION_QUESTIONS = [
 2014 |   "What specific problem does this feature solve?",
 2015 |   "Who are the target users for this feature?",
 2016 |   "What are the key requirements for this feature?",
 2017 |   "What are the technical constraints or considerations?",
 2018 |   "How will we measure the success of this feature?",
 2019 |   "Are there any dependencies on other features or systems?",
 2020 |   "What are the potential risks or challenges in implementing this feature?"
 2021 | ];
 2022 | 
 2023 | /**
 2024 |  * Result when all clarification questions are complete
 2025 |  */
 2026 | export interface ClarificationComplete {
 2027 |   done: true;
 2028 |   message: string;
 2029 | }
 2030 | 
 2031 | /**
 2032 |  * Get the next clarification question for a feature
 2033 |  * @param feature The feature to get the next question for
 2034 |  * @returns The next question to ask or a completion object if all questions have been answered
 2035 |  * @throws Error if the feature is missing the clarificationResponses array
 2036 |  */
 2037 | export function getNextClarificationQuestion(feature: Feature): string | ClarificationComplete {
 2038 |   if (!feature.clarificationResponses) {
 2039 |     // Throw a proper error instead of just logging
 2040 |     throw new Error(`Feature is missing clarificationResponses array: ${feature.id}`);
 2041 |   }
 2042 |   
 2043 |   // Check if we've asked all the default questions
 2044 |   if (feature.clarificationResponses.length >= DEFAULT_CLARIFICATION_QUESTIONS.length) {
 2045 |     return {
 2046 |       done: true,
 2047 |       message: "All clarification questions have been answered. You can now generate a PRD for this feature."
 2048 |     };
 2049 |   }
 2050 |   
 2051 |   // Get the next question based on the number of responses
 2052 |   return DEFAULT_CLARIFICATION_QUESTIONS[feature.clarificationResponses.length];
 2053 | }
 2054 | 
 2055 | /**
 2056 |  * Add a clarification response to a feature
 2057 |  * @param featureId The ID of the feature to add the response to
 2058 |  * @param question The question that was asked
 2059 |  * @param answer The user's answer
 2060 |  * @returns The updated feature
 2061 |  * @throws Error if the feature is not found
 2062 |  */
 2063 | export function addClarificationResponse(
 2064 |   featureId: string,
 2065 |   question: string,
 2066 |   answer: string
 2067 | ): Feature {
 2068 |   const feature = getFeature(featureId);
 2069 |   if (!feature) {
 2070 |     throw new Error(`Feature with ID ${featureId} not found`);
 2071 |   }
 2072 |   
 2073 |   // Create a new response
 2074 |   const newResponse: ClarificationResponse = {
 2075 |     question,
 2076 |     answer,
 2077 |     timestamp: now()
 2078 |   };
 2079 |   
 2080 |   // Update the feature with the new response
 2081 |   const updatedFeature = updateFeature(featureId, {
 2082 |     clarificationResponses: [...feature.clarificationResponses, newResponse]
 2083 |   });
 2084 |   
 2085 |   if (!updatedFeature) {
 2086 |     throw new Error(`Failed to update feature ${featureId} with new clarification response`);
 2087 |   }
 2088 |   
 2089 |   return updatedFeature;
 2090 | }
 2091 | 
 2092 | /**
 2093 |  * Format clarification responses as text
 2094 |  * @param responses The responses to format
 2095 |  * @returns Formatted text
 2096 |  */
 2097 | export function formatClarificationResponses(responses: ClarificationResponse[]): string {
 2098 |   if (!responses || responses.length === 0) {
 2099 |     return "No clarification responses yet.";
 2100 |   }
 2101 |   
 2102 |   return responses.map(cr => `Q: ${cr.question}\nA: ${cr.answer}`).join('\n\n');
 2103 | }
 2104 | 
 2105 | /**
 2106 |  * Check if a feature has completed the clarification process
 2107 |  * @param feature The feature to check
 2108 |  * @returns True if clarification is complete, false otherwise
 2109 |  * @throws Error if the feature is missing the clarificationResponses array
 2110 |  */
 2111 | export function isClarificationComplete(feature: Feature): boolean {
 2112 |   if (!feature.clarificationResponses) {
 2113 |     throw new Error(`Feature is missing clarificationResponses array: ${feature.id}`);
 2114 |   }
 2115 |   
 2116 |   return feature.clarificationResponses.length >= DEFAULT_CLARIFICATION_QUESTIONS.length;
 2117 | }
 2118 | 
 2119 | /**
 2120 |  * Get a summary of the clarification status
 2121 |  * @param feature The feature to get the status for
 2122 |  * @returns A text summary of the clarification status
 2123 |  * @throws Error if the feature is missing the clarificationResponses array
 2124 |  */
 2125 | export function getClarificationStatus(feature: Feature): string {
 2126 |   if (!feature.clarificationResponses) {
 2127 |     throw new Error(`Feature is missing clarificationResponses array: ${feature.id}`);
 2128 |   }
 2129 |   
 2130 |   const total = DEFAULT_CLARIFICATION_QUESTIONS.length;
 2131 |   const completed = feature.clarificationResponses.length;
 2132 |   
 2133 |   return `Clarification progress: ${completed}/${total} questions answered.`;
 2134 | }
 2135 | 
 2136 | ================
 2137 | File: src/documentation.ts
 2138 | ================
 2139 | /**
 2140 |  * Documentation generation functions for the Vibe-Coder MCP Server.
 2141 |  * This module handles generating PRDs and implementation plans from feature clarifications.
 2142 |  */
 2143 | import * as fs from 'fs';
 2144 | import * as path from 'path';
 2145 | import { Feature, ClarificationResponse, Phase } from './types.js';
 2146 | import { formatDate } from './utils.js';
 2147 | 
 2148 | /**
 2149 |  * Load a template file and return its contents
 2150 |  * @param templateName The name of the template file (without the path)
 2151 |  * @returns The template content as a string
 2152 |  * @throws Error if the template cannot be loaded
 2153 |  */
 2154 | function loadTemplate(templateName: string): string {
 2155 |   try {
 2156 |     const templatePath = path.join(process.cwd(), 'src', 'templates', templateName);
 2157 |     return fs.readFileSync(templatePath, 'utf-8');
 2158 |   } catch (error) {
 2159 |     console.error(`Error loading template ${templateName}:`, error);
 2160 |     throw new Error(`Failed to load template ${templateName}: ${error instanceof Error ? error.message : String(error)}`);
 2161 |   }
 2162 | }
 2163 | 
 2164 | /**
 2165 |  * Generate a PRD document from a feature and its clarification responses
 2166 |  * @param feature The feature to generate a PRD for
 2167 |  * @returns The generated PRD markdown content
 2168 |  */
 2169 | export function generatePRD(feature: Feature): string {
 2170 |   try {
 2171 |     const template = loadTemplate('prd-template.md');
 2172 |     
 2173 |     // Replace template variables
 2174 |     return template
 2175 |       .replace(/{{featureName}}/g, feature.name)
 2176 |       .replace(/{{featureDescription}}/g, feature.description || '')
 2177 |       .replace(/{{featureNameSlug}}/g, slugify(feature.name))
 2178 |       .replace(/{{stepNumber}}/g, '01')
 2179 |       .replace(/{{objectives}}/g, extractObjectivesFromClarifications(feature.clarificationResponses))
 2180 |       .replace(/{{requirements}}/g, extractRequirementsFromClarifications(feature.clarificationResponses))
 2181 |       .replace(/{{technicalSpecs}}/g, extractTechnicalSpecsFromClarifications(feature.clarificationResponses))
 2182 |       .replace(/{{implementationPhases}}/g, generateImplementationPhasesList(feature));
 2183 |   } catch (error) {
 2184 |     console.warn(`Template loading failed, falling back to basic PRD: ${error instanceof Error ? error.message : String(error)}`);
 2185 |     return generateBasicPRD(feature);
 2186 |   }
 2187 | }
 2188 | 
 2189 | /**
 2190 |  * Generate a basic PRD as fallback if template loading fails
 2191 |  * @param feature The feature to generate a PRD for
 2192 |  * @returns A basic PRD markdown content
 2193 |  */
 2194 | function generateBasicPRD(feature: Feature): string {
 2195 |   return `# ${feature.name} PRD
 2196 | 
 2197 | ## 1. Introduction
 2198 | 
 2199 | ${feature.description}
 2200 | 
 2201 | ## 2. Feature Objectives
 2202 | 
 2203 | ${extractObjectivesFromClarifications(feature.clarificationResponses)}
 2204 | 
 2205 | ## 3. Scope and Requirements
 2206 | 
 2207 | ${extractRequirementsFromClarifications(feature.clarificationResponses)}
 2208 | 
 2209 | ## 4. Technical Specifications
 2210 | 
 2211 | ${extractTechnicalSpecsFromClarifications(feature.clarificationResponses)}
 2212 | 
 2213 | ## 5. Implementation Phases
 2214 | 
 2215 | ${generateImplementationPhasesList(feature)}
 2216 | 
 2217 | ## 6. Feedback and Iteration Process
 2218 | 
 2219 | This PRD will be updated as the implementation progresses and feedback is received.
 2220 | `;
 2221 | }
 2222 | 
 2223 | /**
 2224 |  * Generate an implementation plan from a feature and its clarification responses
 2225 |  * @param feature The feature to generate an implementation plan for
 2226 |  * @returns The generated implementation plan markdown content
 2227 |  */
 2228 | export function generateImplementationPlan(feature: Feature): string {
 2229 |   try {
 2230 |     const template = loadTemplate('implementation-plan-template.md');
 2231 |     
 2232 |     // Replace template variables
 2233 |     return template
 2234 |       .replace(/{{featureName}}/g, feature.name)
 2235 |       .replace(/{{featureDescription}}/g, feature.description || '')
 2236 |       .replace(/{{featureNameSlug}}/g, slugify(feature.name))
 2237 |       .replace(/{{stepNumber}}/g, '02')
 2238 |       .replace(/{{objectives}}/g, extractObjectivesFromClarifications(feature.clarificationResponses))
 2239 |       .replace(/{{requirements}}/g, extractRequirementsFromClarifications(feature.clarificationResponses))
 2240 |       .replace(/{{technicalSpecs}}/g, extractTechnicalSpecsFromClarifications(feature.clarificationResponses))
 2241 |       .replace(/{{implementationPhases}}/g, generateImplementationPhasesList(feature))
 2242 |       .replace(/{{developmentPhases}}/g, generateDefaultPhases(feature).map(p => `## ${p.name}\n\n${p.description}`).join('\n\n'))
 2243 |       .replace(/{{fileStructure}}/g, generateFileStructure(feature))
 2244 |       .replace(/{{nextSteps}}/g, generateNextSteps(feature).map(step => `- ${step}`).join('\n'));
 2245 |   } catch (error) {
 2246 |     console.warn(`Template loading failed, falling back to basic implementation plan: ${error instanceof Error ? error.message : String(error)}`);
 2247 |     return generateBasicImplementationPlan(feature);
 2248 |   }
 2249 | }
 2250 | 
 2251 | /**
 2252 |  * Generate a basic implementation plan as fallback if template loading fails
 2253 |  * @param feature The feature to generate an implementation plan for
 2254 |  * @returns A basic implementation plan markdown content
 2255 |  */
 2256 | function generateBasicImplementationPlan(feature: Feature): string {
 2257 |   const phases = generateDefaultPhases(feature);
 2258 |   
 2259 |   let phasesContent = '';
 2260 |   phases.forEach((phase, index) => {
 2261 |     phasesContent += `\n### Phase ${index + 1}: ${phase.name}\n\n`;
 2262 |     phasesContent += `**Objectives**: ${phase.objectives}\n\n`;
 2263 |     phasesContent += `**Tasks**:\n`;
 2264 |     phase.tasks.forEach((task: string) => {
 2265 |       phasesContent += `- [ ] ${task}\n`;
 2266 |     });
 2267 |     phasesContent += `\n**Code Style & Practices**: ${phase.codeStyle}\n\n`;
 2268 |   });
 2269 |   
 2270 |   return `# ${feature.name} Implementation Plan
 2271 | 
 2272 | ## Overview
 2273 | 
 2274 | ${feature.description}
 2275 | 
 2276 | ## Implementation Steps
 2277 | ${phasesContent}
 2278 | 
 2279 | ## File Structure
 2280 | 
 2281 | \`\`\`
 2282 | ${generateFileStructure(feature)}
 2283 | \`\`\`
 2284 | 
 2285 | ## Implementation Timeline
 2286 | 
 2287 | ${phases.map((phase, i) => `${i + 1}. **${phase.name}**: ${phase.timeEstimate || '1-2 days'}`).join('\n')}
 2288 | 
 2289 | ## Next Steps
 2290 | 
 2291 | ${generateNextSteps(feature).map((step, i) => `${i + 1}. ${step}`).join('\n')}
 2292 | `;
 2293 | }
 2294 | 
 2295 | /**
 2296 |  * Extract objectives from clarification responses
 2297 |  * @param responses The clarification responses to extract objectives from
 2298 |  * @returns Markdown content for the objectives section
 2299 |  */
 2300 | export function extractObjectivesFromClarifications(responses: ClarificationResponse[]): string {
 2301 |   if (responses.length === 0) {
 2302 |     return "No objectives defined yet. Complete the clarification process to generate objectives.";
 2303 |   }
 2304 |   
 2305 |   // Look for responses related to problems and users
 2306 |   const problemResponse = responses.find(r => r.question.includes("problem"));
 2307 |   const usersResponse = responses.find(r => r.question.includes("users"));
 2308 |   const successResponse = responses.find(r => r.question.includes("success"));
 2309 |   
 2310 |   let objectives = "Based on the clarification responses, this feature aims to:\n\n";
 2311 |   
 2312 |   if (problemResponse) {
 2313 |     objectives += `- **Solve a Problem**: ${problemResponse.answer}\n`;
 2314 |   }
 2315 |   
 2316 |   if (usersResponse) {
 2317 |     objectives += `- **Target Users**: ${usersResponse.answer}\n`;
 2318 |   }
 2319 |   
 2320 |   if (successResponse) {
 2321 |     objectives += `- **Success Criteria**: ${successResponse.answer}\n`;
 2322 |   }
 2323 |   
 2324 |   objectives += "\nThe key objectives are to create a solution that is:\n";
 2325 |   objectives += "- Clean and maintainable\n";
 2326 |   objectives += "- Well-documented\n";
 2327 |   objectives += "- Follows best practices\n";
 2328 |   
 2329 |   return objectives;
 2330 | }
 2331 | 
 2332 | /**
 2333 |  * Extract requirements from clarification responses
 2334 |  * @param responses The clarification responses to extract requirements from
 2335 |  * @returns Markdown content for the requirements section
 2336 |  */
 2337 | export function extractRequirementsFromClarifications(responses: ClarificationResponse[]): string {
 2338 |   if (responses.length === 0) {
 2339 |     return "No requirements defined yet. Complete the clarification process to generate requirements.";
 2340 |   }
 2341 |   
 2342 |   // Look for responses related to requirements
 2343 |   const requirementsResponse = responses.find(r => r.question.includes("requirements"));
 2344 |   const dependenciesResponse = responses.find(r => r.question.includes("dependencies"));
 2345 |   
 2346 |   let requirements = "Based on the clarification responses, this feature requires:\n\n";
 2347 |   
 2348 |   if (requirementsResponse) {
 2349 |     // Split the requirements by common delimiters and format as a list
 2350 |     const reqList = requirementsResponse.answer
 2351 |       .split(/[,.;]/)
 2352 |       .filter(item => item.trim().length > 0)
 2353 |       .map(item => `- ${item.trim()}`);
 2354 |     
 2355 |     requirements += reqList.join('\n');
 2356 |     requirements += '\n\n';
 2357 |   }
 2358 |   
 2359 |   if (dependenciesResponse) {
 2360 |     requirements += `**Dependencies**:\n${dependenciesResponse.answer}\n\n`;
 2361 |   }
 2362 |   
 2363 |   return requirements;
 2364 | }
 2365 | 
 2366 | /**
 2367 |  * Extract technical specifications from clarification responses
 2368 |  * @param responses The clarification responses to extract technical specifications from
 2369 |  * @returns Markdown content for the technical specifications section
 2370 |  */
 2371 | export function extractTechnicalSpecsFromClarifications(responses: ClarificationResponse[]): string {
 2372 |   if (responses.length === 0) {
 2373 |     return "No technical specifications defined yet. Complete the clarification process.";
 2374 |   }
 2375 |   
 2376 |   // Look for responses related to technical constraints
 2377 |   const technicalResponse = responses.find(r => r.question.includes("technical constraints") || r.question.includes("considerations"));
 2378 |   const risksResponse = responses.find(r => r.question.includes("risks") || r.question.includes("challenges"));
 2379 |   
 2380 |   let specs = "";
 2381 |   
 2382 |   if (technicalResponse) {
 2383 |     specs += `**Technical Constraints**:\n${technicalResponse.answer}\n\n`;
 2384 |   }
 2385 |   
 2386 |   if (risksResponse) {
 2387 |     specs += `**Potential Risks and Challenges**:\n${risksResponse.answer}\n\n`;
 2388 |   }
 2389 |   
 2390 |   specs += `**Development Approach**:\n`;
 2391 |   specs += `- Use TypeScript for type safety\n`;
 2392 |   specs += `- Follow functional programming principles\n`;
 2393 |   specs += `- Implement thorough testing\n`;
 2394 |   specs += `- Use modular design\n`;
 2395 |   
 2396 |   return specs;
 2397 | }
 2398 | 
 2399 | /**
 2400 |  * Generate a list of implementation phases for the PRD
 2401 |  * @param feature The feature to generate phases for
 2402 |  * @returns Markdown content for the implementation phases section
 2403 |  */
 2404 | function generateImplementationPhasesList(feature: Feature): string {
 2405 |   const phases = generateDefaultPhases(feature);
 2406 |   
 2407 |   let phasesList = "";
 2408 |   phases.forEach((phase, index) => {
 2409 |     phasesList += `**Phase ${index + 1}: ${phase.name}**\n`;
 2410 |     phasesList += `${phase.objectives}\n\n`;
 2411 |   });
 2412 |   
 2413 |   return phasesList;
 2414 | }
 2415 | 
 2416 | /**
 2417 |  * Generate default implementation phases based on the feature
 2418 |  * @param feature The feature to generate phases for
 2419 |  * @returns An array of phase objects
 2420 |  */
 2421 | function generateDefaultPhases(feature: Feature): any[] {
 2422 |   // If the feature already has phases defined, use those
 2423 |   if (feature.phases && feature.phases.length > 0) {
 2424 |     return feature.phases.map(phase => ({
 2425 |       name: phase.name,
 2426 |       objectives: phase.description,
 2427 |       tasks: phase.tasks.map(task => task.description),
 2428 |       codeStyle: "Follow TypeScript best practices, use functional programming where appropriate, and ensure thorough testing.",
 2429 |       timeEstimate: "1-2 days"
 2430 |     }));
 2431 |   }
 2432 |   
 2433 |   // Otherwise, generate default phases
 2434 |   return [
 2435 |     {
 2436 |       name: "Requirements Analysis and Design",
 2437 |       objectives: "Analyze requirements, design the architecture, and create a detailed implementation plan.",
 2438 |       tasks: [
 2439 |         "Review and analyze clarification responses",
 2440 |         "Identify key components and their interactions",
 2441 |         "Design the system architecture",
 2442 |         "Create UML diagrams if necessary",
 2443 |         "Identify potential edge cases and risks"
 2444 |       ],
 2445 |       codeStyle: "Create clear documentation with diagrams and detailed explanations.",
 2446 |       timeEstimate: "1-2 days"
 2447 |     },
 2448 |     {
 2449 |       name: "Core Implementation",
 2450 |       objectives: "Implement the core functionality based on the design.",
 2451 |       tasks: [
 2452 |         "Set up project structure and dependencies",
 2453 |         "Implement data models and interfaces",
 2454 |         "Build core business logic",
 2455 |         "Create unit tests for core functionality",
 2456 |         "Ensure code follows best practices"
 2457 |       ],
 2458 |       codeStyle: "Use TypeScript with clear typing, follow functional programming principles, and use TDD where appropriate.",
 2459 |       timeEstimate: "2-3 days"
 2460 |     },
 2461 |     {
 2462 |       name: "Testing and Integration",
 2463 |       objectives: "Test all components, integrate with existing systems, and refine the implementation.",
 2464 |       tasks: [
 2465 |         "Write unit tests for all components",
 2466 |         "Perform integration testing",
 2467 |         "Fix bugs and edge cases",
 2468 |         "Optimize performance",
 2469 |         "Document any known limitations"
 2470 |       ],
 2471 |       codeStyle: "Focus on test coverage and quality, fix edge cases, and document limitations.",
 2472 |       timeEstimate: "1-2 days"
 2473 |     },
 2474 |     {
 2475 |       name: "Documentation and Finalization",
 2476 |       objectives: "Finalize documentation, clean up code, and prepare for deployment.",
 2477 |       tasks: [
 2478 |         "Complete inline code documentation",
 2479 |         "Create user documentation",
 2480 |         "Clean up and refactor code",
 2481 |         "Prepare deployment strategy",
 2482 |         "Create final pull request"
 2483 |       ],
 2484 |       codeStyle: "Ensure comprehensive documentation, clean code, and prepare for smooth deployment.",
 2485 |       timeEstimate: "1 day"
 2486 |     }
 2487 |   ];
 2488 | }
 2489 | 
 2490 | /**
 2491 |  * Generate a file structure based on the feature
 2492 |  * @param feature The feature to generate a file structure for
 2493 |  * @returns A string representation of the file structure
 2494 |  */
 2495 | function generateFileStructure(feature: Feature): string {
 2496 |   const featureNameSlug = slugify(feature.name);
 2497 |   
 2498 |   return `src/
 2499 |   ├── ${featureNameSlug}/
 2500 |   │   ├── index.ts                 # Main entry point
 2501 |   │   ├── types.ts                 # Type definitions
 2502 |   │   ├── components/              # UI components (if applicable)
 2503 |   │   │   └── index.ts
 2504 |   │   ├── hooks/                   # Custom hooks (if applicable)
 2505 |   │   │   └── index.ts
 2506 |   │   ├── utils/                   # Utility functions
 2507 |   │   │   └── index.ts
 2508 |   │   └── tests/                   # Tests
 2509 |   │       └── index.test.ts
 2510 |   └── index.ts                     # Re-export public API`;
 2511 | }
 2512 | 
 2513 | /**
 2514 |  * Generate next steps for implementing the feature
 2515 |  * @param feature The feature to generate next steps for
 2516 |  * @returns An array of next steps
 2517 |  */
 2518 | function generateNextSteps(feature: Feature): string[] {
 2519 |   return [
 2520 |     "Set up the project structure and dependencies",
 2521 |     "Implement core functionality based on the PRD",
 2522 |     "Write comprehensive tests for all components",
 2523 |     "Create clear documentation for users and developers",
 2524 |     "Prepare for code review and deployment"
 2525 |   ];
 2526 | }
 2527 | 
 2528 | /**
 2529 |  * Convert a string to a slug format
 2530 |  * @param str The string to convert
 2531 |  * @returns The slug version of the string
 2532 |  */
 2533 | function slugify(str: string): string {
 2534 |   return str
 2535 |     .toLowerCase()
 2536 |     .replace(/[^\w\s-]/g, '')
 2537 |     .replace(/[\s_-]+/g, '-')
 2538 |     .replace(/^-+|-+$/g, '');
 2539 | }
 2540 | 
 2541 | ================
 2542 | File: src/errors.ts
 2543 | ================
 2544 | /**
 2545 |  * @file errors.ts
 2546 |  * @version 1.0.0
 2547 |  * 
 2548 |  * Provides standardized error handling utilities for the Vibe-Coder MCP Server.
 2549 |  * These utilities ensure consistent error responses following the JSON-RPC 2.0 specification.
 2550 |  */
 2551 | 
 2552 | import { z } from 'zod';
 2553 | 
 2554 | // --------- Error Codes ---------
 2555 | 
 2556 | /**
 2557 |  * Standard JSON-RPC 2.0 error codes
 2558 |  * https://www.jsonrpc.org/specification#error_object
 2559 |  */
 2560 | export enum ErrorCode {
 2561 |   // JSON-RPC 2.0 Standard Error Codes
 2562 |   PARSE_ERROR = -32700,
 2563 |   INVALID_REQUEST = -32600,
 2564 |   METHOD_NOT_FOUND = -32601,
 2565 |   INVALID_PARAMS = -32602,
 2566 |   INTERNAL_ERROR = -32603,
 2567 |   
 2568 |   // Custom Error Codes (must be between -32000 and -32099)
 2569 |   VALIDATION_ERROR = -32000,
 2570 |   RESOURCE_NOT_FOUND = -32001,
 2571 |   TOOL_NOT_FOUND = -32002,
 2572 |   PROMPT_NOT_FOUND = -32003,
 2573 |   UNAUTHORIZED = -32004,
 2574 |   FEATURE_NOT_FOUND = -32010,
 2575 |   PHASE_NOT_FOUND = -32011,
 2576 |   TASK_NOT_FOUND = -32012,
 2577 |   INVALID_PHASE_TRANSITION = -32013,
 2578 |   CLARIFICATION_INCOMPLETE = -32014,
 2579 | }
 2580 | 
 2581 | // --------- Error Responses ---------
 2582 | 
 2583 | /**
 2584 |  * Standard JSON-RPC 2.0 error response structure
 2585 |  */
 2586 | export type ErrorResponse = {
 2587 |   error: {
 2588 |     code: ErrorCode;
 2589 |     message: string;
 2590 |     data?: any;
 2591 |   }
 2592 | };
 2593 | 
 2594 | /**
 2595 |  * Tool error response
 2596 |  */
 2597 | export type ToolErrorResponse = {
 2598 |   content: [{
 2599 |     type: "text";
 2600 |     text: string;
 2601 |   }];
 2602 |   isError?: boolean;
 2603 | };
 2604 | 
 2605 | /**
 2606 |  * Create a standard error response for JSON-RPC 2.0
 2607 |  */
 2608 | export const createErrorResponse = (
 2609 |   code: ErrorCode, 
 2610 |   message: string, 
 2611 |   data?: any
 2612 | ): ErrorResponse => {
 2613 |   return {
 2614 |     error: {
 2615 |       code,
 2616 |       message,
 2617 |       data
 2618 |     }
 2619 |   };
 2620 | };
 2621 | 
 2622 | /**
 2623 |  * Create a tool error response
 2624 |  */
 2625 | export const createToolErrorResponse = (
 2626 |   message: string, 
 2627 |   details?: any
 2628 | ): ToolErrorResponse => {
 2629 |   return {
 2630 |     content: [{
 2631 |       type: "text",
 2632 |       text: `Error: ${message}`
 2633 |     }],
 2634 |     isError: true
 2635 |   };
 2636 | };
 2637 | 
 2638 | /**
 2639 |  * Capture and format Zod validation errors
 2640 |  */
 2641 | export const handleZodError = (error: z.ZodError): ErrorResponse => {
 2642 |   const formattedErrors = error.errors.map(err => ({
 2643 |     path: err.path.join('.'),
 2644 |     message: err.message
 2645 |   }));
 2646 |   
 2647 |   return createErrorResponse(
 2648 |     ErrorCode.VALIDATION_ERROR,
 2649 |     "Validation error",
 2650 |     formattedErrors
 2651 |   );
 2652 | };
 2653 | 
 2654 | /**
 2655 |  * Handle feature not found errors
 2656 |  */
 2657 | export const featureNotFoundError = (featureId: string): ToolErrorResponse => {
 2658 |   return createToolErrorResponse(`Feature with ID ${featureId} not found`);
 2659 | };
 2660 | 
 2661 | /**
 2662 |  * Handle phase not found errors
 2663 |  */
 2664 | export const phaseNotFoundError = (
 2665 |   phaseId: string, 
 2666 |   featureName: string
 2667 | ): ToolErrorResponse => {
 2668 |   return createToolErrorResponse(
 2669 |     `Phase with ID ${phaseId} not found in feature ${featureName}`
 2670 |   );
 2671 | };
 2672 | 
 2673 | /**
 2674 |  * Handle task not found errors
 2675 |  */
 2676 | export const taskNotFoundError = (
 2677 |   taskId: string, 
 2678 |   phaseName: string
 2679 | ): ToolErrorResponse => {
 2680 |   return createToolErrorResponse(
 2681 |     `Task with ID ${taskId} not found in phase ${phaseName}`
 2682 |   );
 2683 | };
 2684 | 
 2685 | /**
 2686 |  * Handle invalid phase transition errors
 2687 |  */
 2688 | export const invalidPhaseTransitionError = (
 2689 |   currentStatus: string, 
 2690 |   newStatus: string
 2691 | ): ToolErrorResponse => {
 2692 |   return createToolErrorResponse(
 2693 |     `Cannot transition phase from "${currentStatus}" to "${newStatus}"`
 2694 |   );
 2695 | };
 2696 | 
 2697 | /**
 2698 |  * Handle clarification incomplete errors
 2699 |  */
 2700 | export const clarificationIncompleteError = (
 2701 |   status: any
 2702 | ): ToolErrorResponse => {
 2703 |   return createToolErrorResponse(
 2704 |     `Cannot proceed until clarification is complete`,
 2705 |     { clarificationStatus: status }
 2706 |   );
 2707 | };
 2708 | 
 2709 | /**
 2710 |  * Try-catch wrapper for Zod validation
 2711 |  */
 2712 | export const tryValidate = <T>(
 2713 |   schema: z.ZodType<T>,
 2714 |   data: unknown
 2715 | ): { success: true; data: T } | { success: false; error: ErrorResponse } => {
 2716 |   try {
 2717 |     return { success: true, data: schema.parse(data) };
 2718 |   } catch (error) {
 2719 |     if (error instanceof z.ZodError) {
 2720 |       return { success: false, error: handleZodError(error) };
 2721 |     }
 2722 |     return {
 2723 |       success: false,
 2724 |       error: createErrorResponse(
 2725 |         ErrorCode.INTERNAL_ERROR,
 2726 |         error instanceof Error ? error.message : "Unknown error"
 2727 |       )
 2728 |     };
 2729 |   }
 2730 | };
 2731 | 
 2732 | ================
 2733 | File: src/index-updated.ts
 2734 | ================
 2735 | #!/usr/bin/env node
 2736 | 
 2737 | /**
 2738 |  * @file Vibe-Coder MCP Server
 2739 |  * @version 0.2.0
 2740 |  * 
 2741 |  * This MCP server implements a structured development workflow that helps
 2742 |  * LLM-based coders build features in an organized, clean, and safe manner.
 2743 |  * 
 2744 |  * Core functionalities:
 2745 |  * - Feature request clarification through iterative questioning
 2746 |  * - PRD and implementation plan generation
 2747 |  * - Phased development with tasks and status tracking
 2748 |  */
 2749 | 
 2750 | import { Server } from "@modelcontextprotocol/sdk/server/index.js";
 2751 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
 2752 | import {
 2753 |   CallToolRequestSchema,
 2754 |   ListResourcesRequestSchema,
 2755 |   ListToolsRequestSchema,
 2756 |   ReadResourceRequestSchema,
 2757 |   ListPromptsRequestSchema,
 2758 |   GetPromptRequestSchema,
 2759 |   ResourceTemplate,
 2760 | } from "@modelcontextprotocol/sdk/types.js";
 2761 | 
 2762 | // Import core modules
 2763 | import { Feature, FeatureStorage, PhaseStatus, Phase, Task, ClarificationResponse } from './types.js';
 2764 | import { features, storeFeature, getFeature, updateFeature, listFeatures } from './storage.js';
 2765 | import { 
 2766 |   DEFAULT_CLARIFICATION_QUESTIONS as CLARIFICATION_QUESTIONS, 
 2767 |   getNextClarificationQuestion, 
 2768 |   addClarificationResponse,
 2769 |   formatClarificationResponses,
 2770 |   isClarificationComplete,
 2771 |   getClarificationStatus
 2772 | } from './clarification.js';
 2773 | import { generatePRD, generateImplementationPlan } from './documentation.js';
 2774 | import { createPhase, getPhase, updatePhaseStatus, getNextPhaseStatus, validatePhaseTransition, addTask, updateTaskStatus } from './phases.js';
 2775 | import { generateId, createFeatureObject, createPhaseObject, createTaskObject, generateFeatureProgressSummary, isValidPhaseStatus } from './utils.js';
 2776 | import { validateFeatureId, validatePhaseId, validateTaskId, validateFeaturePhaseTask, validateRequiredText, validatePhaseStatusValue } from './validators.js';
 2777 | import { toolRegistry, resourceRegistry } from './registry.js';
 2778 | import { registerToolHandlers } from './tool-handlers.js';
 2779 | import { registerResourceHandlers } from './resource-handlers.js';
 2780 | import { ErrorCode, createErrorResponse, createToolErrorResponse } from './errors.js';
 2781 | 
 2782 | /**
 2783 |  * Create an MCP server with capabilities for resources, tools, and prompts
 2784 |  */
 2785 | const server = new Server(
 2786 |   {
 2787 |     name: "Vibe-Coder MCP Server",
 2788 |     version: "0.2.0",
 2789 |   },
 2790 |   {
 2791 |     capabilities: {
 2792 |       resources: {}, // Expose resources for features, PRDs, and implementation plans
 2793 |       tools: {},     // Provide tools for feature clarification and development
 2794 |       prompts: {},   // Supply prompts for guiding the development process
 2795 |     },
 2796 |   }
 2797 | );
 2798 | 
 2799 | /**
 2800 |  * Initialize the server by registering all tool and resource handlers
 2801 |  */
 2802 | function initializeServer() {
 2803 |   // Register all tool handlers
 2804 |   registerToolHandlers();
 2805 |   
 2806 |   // Register all resource handlers
 2807 |   registerResourceHandlers();
 2808 |   
 2809 |   console.error("Vibe-Coder MCP Server initialized successfully");
 2810 | }
 2811 | 
 2812 | /**
 2813 |  * Handler for listing available resources.
 2814 |  */
 2815 | server.setRequestHandler(ListResourcesRequestSchema, async () => {
 2816 |   return {
 2817 |     resources: [
 2818 |       {
 2819 |         uri: "features://list",
 2820 |         mimeType: "text/plain",
 2821 |         name: "Features List",
 2822 |         description: "Lists all features being developed"
 2823 |       },
 2824 |       {
 2825 |         uri: "features://status",
 2826 |         mimeType: "text/markdown",
 2827 |         name: "Project Status",
 2828 |         description: "Provides a summary of all features and their development status"
 2829 |       },
 2830 |       ...listFeatures().flatMap(feature => [
 2831 |         {
 2832 |           uri: `feature://${feature.id}`,
 2833 |           mimeType: "text/plain", 
 2834 |           name: feature.name,
 2835 |           description: `Details about feature: ${feature.name}`
 2836 |         },
 2837 |         {
 2838 |           uri: `feature://${feature.id}/progress`,
 2839 |           mimeType: "text/markdown",
 2840 |           name: `${feature.name} Progress Report`,
 2841 |           description: `Detailed progress report for feature: ${feature.name}`
 2842 |         },
 2843 |         {
 2844 |           uri: `feature://${feature.id}/prd`,
 2845 |           mimeType: "text/markdown",
 2846 |           name: `${feature.name} PRD`,
 2847 |           description: `PRD document for feature: ${feature.name}`
 2848 |         },
 2849 |         {
 2850 |           uri: `feature://${feature.id}/implementation`,
 2851 |           mimeType: "text/markdown",
 2852 |           name: `${feature.name} Implementation Plan`,
 2853 |           description: `Implementation plan for feature: ${feature.name}`
 2854 |         },
 2855 |         {
 2856 |           uri: `feature://${feature.id}/phases`,
 2857 |           mimeType: "text/plain",
 2858 |           name: `${feature.name} Phases`,
 2859 |           description: `Lists all phases for feature: ${feature.name}`
 2860 |         },
 2861 |         {
 2862 |           uri: `feature://${feature.id}/tasks`,
 2863 |           mimeType: "text/plain",
 2864 |           name: `${feature.name} All Tasks`,
 2865 |           description: `Lists all tasks across all phases for feature: ${feature.name}`
 2866 |         },
 2867 |         ...feature.phases.flatMap(phase => [
 2868 |           {
 2869 |             uri: `feature://${feature.id}/phase/${phase.id}`,
 2870 |             mimeType: "text/plain",
 2871 |             name: `${feature.name} - ${phase.name}`,
 2872 |             description: `Details about phase: ${phase.name} for feature: ${feature.name}`
 2873 |           },
 2874 |           {
 2875 |             uri: `feature://${feature.id}/phase/${phase.id}/tasks`,
 2876 |             mimeType: "text/plain",
 2877 |             name: `${feature.name} - ${phase.name} Tasks`,
 2878 |             description: `Lists all tasks for phase: ${phase.name}`
 2879 |           },
 2880 |           ...phase.tasks.map(task => ({
 2881 |             uri: `feature://${feature.id}/phase/${phase.id}/task/${task.id}`,
 2882 |             mimeType: "text/plain",
 2883 |             name: `Task: ${task.description.substring(0, 30)}${task.description.length > 30 ? '...' : ''}`,
 2884 |             description: `Details about task: ${task.description.substring(0, 50)}${task.description.length > 50 ? '...' : ''}`
 2885 |           }))
 2886 |         ])
 2887 |       ])
 2888 |     ]
 2889 |   };
 2890 | });
 2891 | 
 2892 | /**
 2893 |  * Handler for reading feature resources.
 2894 |  */
 2895 | server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
 2896 |   try {
 2897 |     const uri = request.params.uri;
 2898 |     
 2899 |     const match = resourceRegistry.findMatch(uri);
 2900 |     
 2901 |     if (match) {
 2902 |       return await match.handler(new URL(uri), match.params);
 2903 |     }
 2904 |     
 2905 |     return createErrorResponse(
 2906 |       ErrorCode.RESOURCE_NOT_FOUND,
 2907 |       `Resource not found: ${uri}`
 2908 |     );
 2909 |   } catch (error: any) {
 2910 |     console.error(`Error reading resource ${request.params.uri}:`, error);
 2911 |     return createErrorResponse(
 2912 |       ErrorCode.INTERNAL_ERROR,
 2913 |       error.message || 'Unknown error'
 2914 |     );
 2915 |   }
 2916 | });
 2917 | 
 2918 | /**
 2919 |  * Handler that lists available tools.
 2920 |  */
 2921 | server.setRequestHandler(ListToolsRequestSchema, async () => {
 2922 |   return {
 2923 |     tools: toolRegistry.listTools()
 2924 |   };
 2925 | });
 2926 | 
 2927 | /**
 2928 |  * Handler for implementing MCP tools.
 2929 |  */
 2930 | server.setRequestHandler(CallToolRequestSchema, async (request) => {
 2931 |   try {
 2932 |     const toolName = request.params.name;
 2933 |     const toolArguments = request.params.arguments || {};
 2934 |     
 2935 |     // Execute the tool using the tool registry
 2936 |     return await toolRegistry.execute(toolName, toolArguments);
 2937 |   } catch (error: any) {
 2938 |     console.error('Error executing tool:', error);
 2939 |     return createToolErrorResponse(`An unexpected error occurred: ${error.message || 'Unknown error'}`);
 2940 |   }
 2941 | });
 2942 | 
 2943 | /**
 2944 |  * Handler that lists available prompts.
 2945 |  */
 2946 | server.setRequestHandler(ListPromptsRequestSchema, async () => {
 2947 |   return {
 2948 |     prompts: [
 2949 |       {
 2950 |         name: "clarify_feature",
 2951 |         description: "Guide to clarify a feature request through questioning"
 2952 |       }
 2953 |     ]
 2954 |   };
 2955 | });
 2956 | 
 2957 | /**
 2958 |  * Handler for the clarify_feature prompt.
 2959 |  */
 2960 | server.setRequestHandler(GetPromptRequestSchema, async (request) => {
 2961 |   if (request.params.name === "clarify_feature") {
 2962 |     return {
 2963 |       messages: [
 2964 |         {
 2965 |           role: "user",
 2966 |           content: {
 2967 |             type: "text",
 2968 |             text: "Help me clarify this feature request by asking questions about:"
 2969 |           }
 2970 |         },
 2971 |         {
 2972 |           role: "user",
 2973 |           content: {
 2974 |             type: "text",
 2975 |             text: "1. The specific problem it solves\n2. The target users\n3. Key requirements\n4. Success criteria\n5. Technical constraints\n\nAsk one question at a time, analyze the response, then proceed to the next most relevant question."
 2976 |           }
 2977 |         }
 2978 |       ]
 2979 |     };
 2980 |   }
 2981 |   
 2982 |   return createErrorResponse(
 2983 |     ErrorCode.PROMPT_NOT_FOUND,
 2984 |     `Unknown prompt: ${request.params.name}`
 2985 |   );
 2986 | });
 2987 | 
 2988 | /**
 2989 |  * Start the server using stdio transport.
 2990 |  */
 2991 | async function main() {
 2992 |   console.error("Starting Vibe-Coder MCP Server...");
 2993 |   
 2994 |   // Initialize the server
 2995 |   initializeServer();
 2996 |   
 2997 |   const transport = new StdioServerTransport();
 2998 |   await server.connect(transport);
 2999 | }
 3000 | 
 3001 | main().catch((error) => {
 3002 |   console.error("Server error:", error);
 3003 |   process.exit(1);
 3004 | });
 3005 | 
 3006 | ================
 3007 | File: src/index.ts
 3008 | ================
 3009 | #!/usr/bin/env node
 3010 | 
 3011 | /**
 3012 |  * @file Vibe-Coder MCP Server
 3013 |  * @version 0.1.0
 3014 |  * 
 3015 |  * This MCP server implements a structured development workflow that helps
 3016 |  * LLM-based coders build features in an organized, clean, and safe manner.
 3017 |  * 
 3018 |  * Core functionalities:
 3019 |  * - Feature request clarification through iterative questioning
 3020 |  * - PRD and implementation plan generation
 3021 |  * - Phased development with tasks and status tracking
 3022 |  */
 3023 | 
 3024 | import { Server } from "@modelcontextprotocol/sdk/server/index.js";
 3025 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
 3026 | import {
 3027 |   CallToolRequestSchema,
 3028 |   ListResourcesRequestSchema,
 3029 |   ListToolsRequestSchema,
 3030 |   ReadResourceRequestSchema,
 3031 |   ListPromptsRequestSchema,
 3032 |   GetPromptRequestSchema,
 3033 | } from "@modelcontextprotocol/sdk/types.js";
 3034 | 
 3035 | // Import core modules
 3036 | import { Feature, FeatureStorage, PhaseStatus, Phase, Task, ClarificationResponse } from './types.js';
 3037 | import { features, storeFeature, getFeature, updateFeature, listFeatures } from './storage.js';
 3038 | import { 
 3039 |   DEFAULT_CLARIFICATION_QUESTIONS as CLARIFICATION_QUESTIONS, 
 3040 |   getNextClarificationQuestion, 
 3041 |   addClarificationResponse,
 3042 |   formatClarificationResponses,
 3043 |   isClarificationComplete,
 3044 |   getClarificationStatus
 3045 | } from './clarification.js';
 3046 | import {
 3047 |   generatePRD,
 3048 |   generateImplementationPlan,
 3049 |   extractObjectivesFromClarifications,
 3050 |   extractRequirementsFromClarifications,
 3051 |   extractTechnicalSpecsFromClarifications
 3052 | } from './documentation.js';
 3053 | import { 
 3054 |   createPhase, 
 3055 |   getPhase, 
 3056 |   updatePhaseStatus,
 3057 |   getNextPhaseStatus,
 3058 |   validatePhaseTransition,
 3059 |   addTask,
 3060 |   updateTaskStatus
 3061 | } from './phases.js';
 3062 | import { 
 3063 |   generateId, 
 3064 |   createFeatureObject,
 3065 |   createPhaseObject,
 3066 |   createTaskObject,
 3067 |   generateFeatureProgressSummary,
 3068 |   isValidPhaseStatus
 3069 | } from './utils.js';
 3070 | import { validateFeatureId, validatePhaseId, validateTaskId, validateFeaturePhaseTask, validateRequiredText, validatePhaseStatusValue } from './validators.js';
 3071 | 
 3072 | /**
 3073 |  * Type alias for a note object.
 3074 |  */
 3075 | type Note = { title: string, content: string };
 3076 | 
 3077 | /**
 3078 |  * Simple in-memory storage for notes.
 3079 |  * In a real implementation, this would likely be backed by a database.
 3080 |  */
 3081 | const notes: { [id: string]: Note } = {
 3082 |   "1": { title: "First Note", content: "This is note 1" },
 3083 |   "2": { title: "Second Note", content: "This is note 2" }
 3084 | };
 3085 | 
 3086 | /**
 3087 |  * Create an MCP server with capabilities for resources, tools, and prompts
 3088 |  */
 3089 | const server = new Server(
 3090 |   {
 3091 |     name: "Vibe-Coder MCP Server",
 3092 |     version: "0.1.0",
 3093 |   },
 3094 |   {
 3095 |     capabilities: {
 3096 |       resources: {}, // Expose resources for features, PRDs, and implementation plans
 3097 |       tools: {},     // Provide tools for feature clarification and development
 3098 |       prompts: {},   // Supply prompts for guiding the development process
 3099 |     },
 3100 |   }
 3101 | );
 3102 | 
 3103 | /**
 3104 |  * Handler for listing available resources.
 3105 |  * Exposes:
 3106 |  * - A list of all features
 3107 |  * - Individual feature details
 3108 |  * - PRD and implementation plan documents
 3109 |  * - Phase and task details
 3110 |  */
 3111 | server.setRequestHandler(ListResourcesRequestSchema, async () => {
 3112 |   return {
 3113 |     resources: [
 3114 |       {
 3115 |         uri: "features://list",
 3116 |         mimeType: "text/plain",
 3117 |         name: "Features List",
 3118 |         description: "Lists all features being developed"
 3119 |       },
 3120 |       {
 3121 |         uri: "features://status",
 3122 |         mimeType: "text/markdown",
 3123 |         name: "Project Status",
 3124 |         description: "Provides a summary of all features and their development status"
 3125 |       },
 3126 |       ...listFeatures().flatMap(feature => [
 3127 |         {
 3128 |           uri: `feature://${feature.id}`,
 3129 |           mimeType: "text/plain", 
 3130 |           name: feature.name,
 3131 |           description: `Details about feature: ${feature.name}`
 3132 |         },
 3133 |         {
 3134 |           uri: `feature://${feature.id}/progress`,
 3135 |           mimeType: "text/markdown",
 3136 |           name: `${feature.name} Progress Report`,
 3137 |           description: `Detailed progress report for feature: ${feature.name}`
 3138 |         },
 3139 |         {
 3140 |           uri: `feature://${feature.id}/prd`,
 3141 |           mimeType: "text/markdown",
 3142 |           name: `${feature.name} PRD`,
 3143 |           description: `PRD document for feature: ${feature.name}`
 3144 |         },
 3145 |         {
 3146 |           uri: `feature://${feature.id}/implementation`,
 3147 |           mimeType: "text/markdown",
 3148 |           name: `${feature.name} Implementation Plan`,
 3149 |           description: `Implementation plan for feature: ${feature.name}`
 3150 |         },
 3151 |         {
 3152 |           uri: `feature://${feature.id}/phases`,
 3153 |           mimeType: "text/plain",
 3154 |           name: `${feature.name} Phases`,
 3155 |           description: `Lists all phases for feature: ${feature.name}`
 3156 |         },
 3157 |         {
 3158 |           uri: `feature://${feature.id}/tasks`,
 3159 |           mimeType: "text/plain",
 3160 |           name: `${feature.name} All Tasks`,
 3161 |           description: `Lists all tasks across all phases for feature: ${feature.name}`
 3162 |         },
 3163 |         ...feature.phases.flatMap(phase => [
 3164 |           {
 3165 |             uri: `feature://${feature.id}/phase/${phase.id}`,
 3166 |             mimeType: "text/plain",
 3167 |             name: `${feature.name} - ${phase.name}`,
 3168 |             description: `Details about phase: ${phase.name} for feature: ${feature.name}`
 3169 |           },
 3170 |           {
 3171 |             uri: `feature://${feature.id}/phase/${phase.id}/tasks`,
 3172 |             mimeType: "text/plain",
 3173 |             name: `${feature.name} - ${phase.name} Tasks`,
 3174 |             description: `Lists all tasks for phase: ${phase.name}`
 3175 |           },
 3176 |           ...phase.tasks.map(task => ({
 3177 |             uri: `feature://${feature.id}/phase/${phase.id}/task/${task.id}`,
 3178 |             mimeType: "text/plain",
 3179 |             name: `Task: ${task.description.substring(0, 30)}${task.description.length > 30 ? '...' : ''}`,
 3180 |             description: `Details about task: ${task.description.substring(0, 50)}${task.description.length > 50 ? '...' : ''}`
 3181 |           }))
 3182 |         ])
 3183 |       ])
 3184 |     ]
 3185 |   };
 3186 | });
 3187 | 
 3188 | /**
 3189 |  * Handler for reading feature resources.
 3190 |  * Supports:
 3191 |  * - List of all features
 3192 |  * - Individual feature details
 3193 |  * - PRD and implementation plan documents
 3194 |  * - Phase and task details
 3195 |  */
 3196 | server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
 3197 |   try {
 3198 |     const url = new URL(request.params.uri);
 3199 |     
 3200 |     // Handle list of all features
 3201 |     if (url.protocol === "features:") {
 3202 |       if (url.pathname === "/list") {
 3203 |         return {
 3204 |           contents: [{
 3205 |             uri: request.params.uri,
 3206 |             mimeType: "text/plain",
 3207 |             text: listFeatures().map(f => `${f.id}: ${f.name}`).join("\n")
 3208 |           }]
 3209 |         };
 3210 |       }
 3211 |       
 3212 |       if (url.pathname === "/status") {
 3213 |         const features = listFeatures();
 3214 |         
 3215 |         if (features.length === 0) {
 3216 |           return {
 3217 |             contents: [{
 3218 |               uri: request.params.uri,
 3219 |               mimeType: "text/markdown",
 3220 |               text: "# Project Status\n\nNo features have been created yet."
 3221 |             }]
 3222 |           };
 3223 |         }
 3224 |         
 3225 |         const featuresStatus = features.map(feature => {
 3226 |           const totalPhases = feature.phases.length;
 3227 |           const completedPhases = feature.phases.filter(p => p.status === 'completed' || p.status === 'reviewed').length;
 3228 |           const totalTasks = feature.phases.reduce((acc, phase) => acc + phase.tasks.length, 0);
 3229 |           const completedTasks = feature.phases.reduce(
 3230 |             (acc, phase) => acc + phase.tasks.filter(t => t.completed).length, 0
 3231 |           );
 3232 |           
 3233 |           return `## ${feature.name}
 3234 | - ID: ${feature.id}
 3235 | - Status: ${completedPhases === totalPhases && totalPhases > 0 ? 'Completed' : 'In Progress'}
 3236 | - Phases: ${completedPhases}/${totalPhases} completed
 3237 | - Tasks: ${completedTasks}/${totalTasks} completed
 3238 | - [View Details](feature://${feature.id}/progress)
 3239 | `;
 3240 |         }).join('\n');
 3241 |         
 3242 |         return {
 3243 |           contents: [{
 3244 |             uri: request.params.uri,
 3245 |             mimeType: "text/markdown",
 3246 |             text: `# Project Status\n\n${featuresStatus}`
 3247 |           }]
 3248 |         };
 3249 |       }
 3250 |     }
 3251 |     
 3252 |     // Handle feature-specific resources
 3253 |     if (url.protocol === "feature:") {
 3254 |       // The hostname part is actually our feature ID in feature:// URLs
 3255 |       let featureId = "";
 3256 |       
 3257 |       if (url.hostname) {
 3258 |         featureId = url.hostname;
 3259 |       } else {
 3260 |         // Try to get feature ID from pathname for backward compatibility
 3261 |         const parts = url.pathname.split('/').filter(Boolean);
 3262 |         if (parts.length > 0) {
 3263 |           featureId = parts[0];
 3264 |         }
 3265 |       }
 3266 |       
 3267 |       if (!featureId) {
 3268 |         throw new Error(`Invalid feature URI: ${request.params.uri}. Missing feature ID.`);
 3269 |       }
 3270 |       
 3271 |       const feature = getFeature(featureId);
 3272 |       
 3273 |       if (!feature) {
 3274 |         throw new Error(`Feature ${featureId} not found`);
 3275 |       }
 3276 |       
 3277 |       // Extract path parts, excluding empty strings
 3278 |       const parts = url.pathname.split('/').filter(Boolean);
 3279 |       
 3280 |       // Return feature details - no additional path parts beyond the feature ID
 3281 |       if (parts.length === 0) {
 3282 |         const timestamp = feature.updatedAt.toISOString();
 3283 |         const clarifications = formatClarificationResponses(feature.clarificationResponses);
 3284 |         const phasesText = feature.phases.map(p => 
 3285 |           `- ${p.name} (${p.status}): ${p.tasks.filter(t => t.completed).length}/${p.tasks.length} tasks completed`
 3286 |         ).join('\n');
 3287 |         
 3288 |         const featureDetails = `
 3289 | Feature: ${feature.name}
 3290 | ID: ${feature.id}
 3291 | Description: ${feature.description}
 3292 | Last Updated: ${timestamp}
 3293 | 
 3294 | Clarification Responses:
 3295 | ${clarifications}
 3296 | 
 3297 | Phases (${feature.phases.length}):
 3298 | ${phasesText}
 3299 | `;
 3300 |         
 3301 |         return {
 3302 |           contents: [{
 3303 |             uri: request.params.uri,
 3304 |             mimeType: "text/plain",
 3305 |             text: featureDetails
 3306 |           }]
 3307 |         };
 3308 |       }
 3309 |       
 3310 |       // Resource is a sub-resource of the feature
 3311 |       if (parts.length >= 1) {
 3312 |         const subResource = parts[0];
 3313 |         
 3314 |         // Return feature progress report
 3315 |         if (subResource === "progress") {
 3316 |           const progressReport = generateFeatureProgressSummary(feature);
 3317 |           
 3318 |           return {
 3319 |             contents: [{
 3320 |               uri: request.params.uri,
 3321 |               mimeType: "text/markdown",
 3322 |               text: progressReport
 3323 |             }]
 3324 |           };
 3325 |         }
 3326 |         
 3327 |         // Return PRD document
 3328 |         if (subResource === "prd") {
 3329 |           const prdContent = feature.prdDoc || generatePRD(feature);
 3330 |           
 3331 |           return {
 3332 |             contents: [{
 3333 |               uri: request.params.uri,
 3334 |               mimeType: "text/markdown",
 3335 |               text: prdContent
 3336 |             }]
 3337 |           };
 3338 |         }
 3339 |         
 3340 |         // Return implementation plan document
 3341 |         if (subResource === "implementation") {
 3342 |           const implContent = feature.implDoc || generateImplementationPlan(feature);
 3343 |           
 3344 |           return {
 3345 |             contents: [{
 3346 |               uri: request.params.uri,
 3347 |               mimeType: "text/markdown",
 3348 |               text: implContent
 3349 |             }]
 3350 |           };
 3351 |         }
 3352 |         
 3353 |         // Return phase listing
 3354 |         if (subResource === "phases") {
 3355 |           if (feature.phases.length === 0) {
 3356 |             return {
 3357 |               contents: [{
 3358 |                 uri: request.params.uri,
 3359 |                 mimeType: "text/plain",
 3360 |                 text: `No phases defined for feature: ${feature.name}`
 3361 |               }]
 3362 |             };
 3363 |           }
 3364 |           
 3365 |           const phasesContent = feature.phases.map(phase => {
 3366 |             const completedTasks = phase.tasks.filter(t => t.completed).length;
 3367 |             const totalTasks = phase.tasks.length;
 3368 |             return `Phase: ${phase.name} (ID: ${phase.id})
 3369 | Status: ${phase.status}
 3370 | Description: ${phase.description}
 3371 | Progress: ${completedTasks}/${totalTasks} tasks completed
 3372 | Last Updated: ${phase.updatedAt.toISOString()}
 3373 | `;
 3374 |           }).join('\n---\n\n');
 3375 |           
 3376 |           return {
 3377 |             contents: [{
 3378 |               uri: request.params.uri,
 3379 |               mimeType: "text/plain",
 3380 |               text: `# Phases for Feature: ${feature.name}\n\n${phasesContent}`
 3381 |             }]
 3382 |           };
 3383 |         }
 3384 |         
 3385 |         // Handle list of all tasks for a feature
 3386 |         if (subResource === "tasks") {
 3387 |           const allTasks = feature.phases.flatMap(phase => 
 3388 |             phase.tasks.map(task => ({
 3389 |               ...task,
 3390 |               phaseName: phase.name,
 3391 |               phaseId: phase.id,
 3392 |               phaseStatus: phase.status
 3393 |             }))
 3394 |           );
 3395 |           
 3396 |           if (allTasks.length === 0) {
 3397 |             return {
 3398 |               contents: [{
 3399 |                 uri: request.params.uri,
 3400 |                 mimeType: "text/plain",
 3401 |                 text: `No tasks defined for feature: ${feature.name}`
 3402 |               }]
 3403 |             };
 3404 |           }
 3405 |           
 3406 |           const pendingTasks = allTasks.filter(t => !t.completed);
 3407 |           const completedTasks = allTasks.filter(t => t.completed);
 3408 |           
 3409 |           const pendingTasksText = pendingTasks.length > 0 
 3410 |             ? pendingTasks.map(task => `- [ ] ${task.description} (ID: ${task.id}, Phase: ${task.phaseName})`).join('\n')
 3411 |             : "No pending tasks.";
 3412 |             
 3413 |           const completedTasksText = completedTasks.length > 0
 3414 |             ? completedTasks.map(task => `- [x] ${task.description} (ID: ${task.id}, Phase: ${task.phaseName})`).join('\n')
 3415 |             : "No completed tasks.";
 3416 |           
 3417 |           const tasksContent = `# All Tasks for Feature: ${feature.name}
 3418 | 
 3419 | ## Pending Tasks (${pendingTasks.length})
 3420 | ${pendingTasksText}
 3421 | 
 3422 | ## Completed Tasks (${completedTasks.length})
 3423 | ${completedTasksText}
 3424 | `;
 3425 |           
 3426 |           return {
 3427 |             contents: [{
 3428 |               uri: request.params.uri,
 3429 |               mimeType: "text/plain",
 3430 |               text: tasksContent
 3431 |             }]
 3432 |           };
 3433 |         }
 3434 |         
 3435 |         // Handle phase-specific resources
 3436 |         if (subResource === "phase" && parts.length >= 2) {
 3437 |           const phaseId = parts[1];
 3438 |           const phase = feature.phases.find(p => p.id === phaseId);
 3439 |           
 3440 |           if (!phase) {
 3441 |             throw new Error(`Phase ${phaseId} not found in feature ${feature.name}`);
 3442 |           }
 3443 |           
 3444 |           // Return phase details
 3445 |           if (parts.length === 2) {
 3446 |             const completedTasks = phase.tasks.filter(t => t.completed).length;
 3447 |             const totalTasks = phase.tasks.length;
 3448 |             
 3449 |             const taskList = phase.tasks.map(task => 
 3450 |               `- [${task.completed ? 'x' : ' '}] ${task.description} (ID: ${task.id})`
 3451 |             ).join('\n');
 3452 |             
 3453 |             const phaseDetails = `
 3454 | Phase: ${phase.name}
 3455 | ID: ${phase.id}
 3456 | Status: ${phase.status}
 3457 | Description: ${phase.description}
 3458 | Created: ${phase.createdAt.toISOString()}
 3459 | Last Updated: ${phase.updatedAt.toISOString()}
 3460 | Progress: ${completedTasks}/${totalTasks} tasks completed
 3461 | 
 3462 | Tasks:
 3463 | ${taskList}
 3464 | `;
 3465 |             
 3466 |             return {
 3467 |               contents: [{
 3468 |                 uri: request.params.uri,
 3469 |                 mimeType: "text/plain",
 3470 |                 text: phaseDetails
 3471 |               }]
 3472 |             };
 3473 |           }
 3474 |           
 3475 |           // Return task listing
 3476 |           if (parts[2] === "tasks") {
 3477 |             if (phase.tasks.length === 0) {
 3478 |               return {
 3479 |                 contents: [{
 3480 |                   uri: request.params.uri,
 3481 |                   mimeType: "text/plain",
 3482 |                   text: `No tasks defined for phase: ${phase.name}`
 3483 |                 }]
 3484 |               };
 3485 |             }
 3486 |             
 3487 |             const tasksContent = phase.tasks.map(task => `
 3488 | Task: ${task.description}
 3489 | ID: ${task.id}
 3490 | Status: ${task.completed ? 'Completed' : 'Pending'}
 3491 | Created: ${task.createdAt.toISOString()}
 3492 | Last Updated: ${task.updatedAt.toISOString()}
 3493 | `).join('\n---\n');
 3494 |             
 3495 |             return {
 3496 |               contents: [{
 3497 |                 uri: request.params.uri,
 3498 |                 mimeType: "text/plain",
 3499 |                 text: `# Tasks for Phase: ${phase.name}\n\n${tasksContent}`
 3500 |               }]
 3501 |             };
 3502 |           }
 3503 |           
 3504 |           // Return individual task details
 3505 |           if (parts[2] === "task" && parts.length === 4) {
 3506 |             const taskId = parts[3];
 3507 |             const task = phase.tasks.find(t => t.id === taskId);
 3508 |             
 3509 |             if (!task) {
 3510 |               throw new Error(`Task ${taskId} not found in phase ${phase.name}`);
 3511 |             }
 3512 |             
 3513 |             const taskDetails = `
 3514 | Task: ${task.description}
 3515 | ID: ${task.id}
 3516 | Status: ${task.completed ? 'Completed' : 'Pending'}
 3517 | Created: ${task.createdAt.toISOString()}
 3518 | Last Updated: ${task.updatedAt.toISOString()}
 3519 | `;
 3520 |             
 3521 |             return {
 3522 |               contents: [{
 3523 |                 uri: request.params.uri,
 3524 |                 mimeType: "text/plain",
 3525 |                 text: taskDetails
 3526 |               }]
 3527 |             };
 3528 |           }
 3529 |         }
 3530 |       }
 3531 |     }
 3532 |     
 3533 |     throw new Error(`Resource not found: ${request.params.uri}`);
 3534 |   } catch (error: any) {
 3535 |     console.error(`Error reading resource ${request.params.uri}:`, error);
 3536 |     return {
 3537 |       contents: [{
 3538 |         uri: request.params.uri,
 3539 |         mimeType: "text/plain",
 3540 |         text: `Error: ${error.message || 'Unknown error'}`
 3541 |       }]
 3542 |     };
 3543 |   }
 3544 | });
 3545 | 
 3546 | /**
 3547 |  * Handler that lists available tools.
 3548 |  * Exposes tools for feature clarification and development.
 3549 |  */
 3550 | server.setRequestHandler(ListToolsRequestSchema, async () => {
 3551 |   return {
 3552 |     tools: [
 3553 |       {
 3554 |         name: "start_feature_clarification",
 3555 |         description: "Start the clarification process for a new feature",
 3556 |         inputSchema: {
 3557 |           type: "object",
 3558 |           properties: {
 3559 |             featureName: {
 3560 |               type: "string",
 3561 |               description: "Name of the feature"
 3562 |             },
 3563 |             initialDescription: {
 3564 |               type: "string",
 3565 |               description: "Initial description of the feature"
 3566 |             }
 3567 |           },
 3568 |           required: ["featureName"],
 3569 |           examples: [
 3570 |             {
 3571 |               featureName: "User Authentication",
 3572 |               initialDescription: "Add login and registration functionality to the application"
 3573 |             },
 3574 |             {
 3575 |               featureName: "Data Export",
 3576 |               initialDescription: "Allow users to export their data in CSV and JSON formats"
 3577 |             }
 3578 |           ]
 3579 |         }
 3580 |       },
 3581 |       {
 3582 |         name: "provide_clarification",
 3583 |         description: "Provide answer to a clarification question",
 3584 |         inputSchema: {
 3585 |           type: "object",
 3586 |           properties: {
 3587 |             featureId: {
 3588 |               type: "string",
 3589 |               description: "ID of the feature"
 3590 |             },
 3591 |             question: {
 3592 |               type: "string",
 3593 |               description: "Clarification question"
 3594 |             },
 3595 |             answer: {
 3596 |               type: "string",
 3597 |               description: "Answer to the clarification question"
 3598 |             }
 3599 |           },
 3600 |           required: ["featureId", "question", "answer"],
 3601 |           examples: [
 3602 |             {
 3603 |               featureId: "feature-123",
 3604 |               question: "What problem does this feature solve?",
 3605 |               answer: "This feature solves the problem of users forgetting their passwords by providing a secure password reset flow."
 3606 |             },
 3607 |             {
 3608 |               featureId: "feature-456",
 3609 |               question: "Who are the target users?",
 3610 |               answer: "The target users are administrators who need to manage user accounts and permissions."
 3611 |             }
 3612 |           ]
 3613 |         }
 3614 |       },
 3615 |       {
 3616 |         name: "generate_prd",
 3617 |         description: "Generate a PRD document based on clarification responses",
 3618 |         inputSchema: {
 3619 |           type: "object",
 3620 |           properties: {
 3621 |             featureId: {
 3622 |               type: "string",
 3623 |               description: "ID of the feature"
 3624 |             }
 3625 |           },
 3626 |           required: ["featureId"],
 3627 |           examples: [
 3628 |             {
 3629 |               featureId: "feature-123"
 3630 |             }
 3631 |           ]
 3632 |         },
 3633 |         handler: async (params: {featureId: string}) => {
 3634 |           const { featureId } = params;
 3635 |           const feature = getFeature(featureId);
 3636 |           
 3637 |           if (!feature) {
 3638 |             return {
 3639 |               error: `Feature with ID ${featureId} not found`
 3640 |             };
 3641 |           }
 3642 |           
 3643 |           if (!isClarificationComplete(feature)) {
 3644 |             return {
 3645 |               error: 'Cannot generate PRD until clarification is complete',
 3646 |               clarificationStatus: getClarificationStatus(feature)
 3647 |             };
 3648 |           }
 3649 |           
 3650 |           // Generate the PRD
 3651 |           const prd = generatePRD(feature);
 3652 |           
 3653 |           // Update the feature with the PRD
 3654 |           updateFeature(featureId, {
 3655 |             ...feature,
 3656 |             prd,
 3657 |             updatedAt: new Date()
 3658 |           });
 3659 |           
 3660 |           return {
 3661 |             success: true,
 3662 |             message: `PRD generated for feature ${feature.name}`,
 3663 |             prd
 3664 |           };
 3665 |         }
 3666 |       },
 3667 |       {
 3668 |         name: 'generate_implementation_plan',
 3669 |         description: 'Generate an implementation plan for a feature based on clarifications and PRD',
 3670 |         inputSchema: {
 3671 |           type: 'object',
 3672 |           properties: {
 3673 |             featureId: {
 3674 |               type: 'string',
 3675 |               description: 'The ID of the feature to generate an implementation plan for'
 3676 |             }
 3677 |           },
 3678 |           required: ['featureId']
 3679 |         },
 3680 |         handler: async (params: {featureId: string}) => {
 3681 |           const { featureId } = params;
 3682 |           const feature = getFeature(featureId);
 3683 |           
 3684 |           if (!feature) {
 3685 |             return {
 3686 |               error: `Feature with ID ${featureId} not found`
 3687 |             };
 3688 |           }
 3689 |           
 3690 |           if (!isClarificationComplete(feature)) {
 3691 |             return {
 3692 |               error: 'Cannot generate implementation plan until clarification is complete',
 3693 |               clarificationStatus: getClarificationStatus(feature)
 3694 |             };
 3695 |           }
 3696 |           
 3697 |           // Generate the implementation plan
 3698 |           const implementationPlan = generateImplementationPlan(feature);
 3699 |           
 3700 |           // Update the feature with the implementation plan
 3701 |           updateFeature(featureId, {
 3702 |             ...feature,
 3703 |             implementationPlan,
 3704 |             updatedAt: new Date()
 3705 |           });
 3706 |           
 3707 |           return {
 3708 |             success: true,
 3709 |             message: `Implementation plan generated for feature ${feature.name}`,
 3710 |             implementationPlan
 3711 |           };
 3712 |         }
 3713 |       },
 3714 |       {
 3715 |         name: 'create_phase',
 3716 |         description: 'Create a new development phase for a feature',
 3717 |         inputSchema: {
 3718 |           type: 'object',
 3719 |           properties: {
 3720 |             featureId: {
 3721 |               type: 'string',
 3722 |               description: 'ID of the feature to create a phase for'
 3723 |             },
 3724 |             name: {
 3725 |               type: 'string',
 3726 |               description: 'Name of the phase'
 3727 |             },
 3728 |             description: {
 3729 |               type: 'string',
 3730 |               description: 'Description of the phase'
 3731 |             }
 3732 |           },
 3733 |           required: ['featureId', 'name', 'description'],
 3734 |           examples: [
 3735 |             {
 3736 |               featureId: "feature-123",
 3737 |               name: "Requirements Analysis",
 3738 |               description: "Gather and analyze requirements for the feature"
 3739 |             },
 3740 |             {
 3741 |               featureId: "feature-123",
 3742 |               name: "Implementation",
 3743 |               description: "Implement the core functionality of the feature"
 3744 |             }
 3745 |           ]
 3746 |         },
 3747 |         handler: async (params: {featureId: string, name: string, description: string}) => {
 3748 |           const { featureId, name, description } = params;
 3749 |           const feature = getFeature(featureId);
 3750 |           
 3751 |           if (!feature) {
 3752 |             return {
 3753 |               error: `Feature with ID ${featureId} not found`
 3754 |             };
 3755 |           }
 3756 |           
 3757 |           // Create the phase with validated inputs
 3758 |           const phaseId = generateId();
 3759 |           const phase = createPhase(feature.id, name, description);
 3760 |           
 3761 |           return {
 3762 |             success: true,
 3763 |             message: `Phase ${name} created for feature ${feature.name}`,
 3764 |             phase
 3765 |           };
 3766 |         }
 3767 |       },
 3768 |       {
 3769 |         name: 'update_phase_status',
 3770 |         description: 'Update the status of a development phase',
 3771 |         inputSchema: {
 3772 |           type: 'object',
 3773 |           properties: {
 3774 |             featureId: {
 3775 |               type: 'string',
 3776 |               description: 'ID of the feature containing the phase'
 3777 |             },
 3778 |             phaseId: {
 3779 |               type: 'string',
 3780 |               description: 'ID of the phase to update'
 3781 |             },
 3782 |             status: {
 3783 |               type: 'string',
 3784 |               description: 'New status for the phase (pending, in_progress, completed, reviewed)'
 3785 |             }
 3786 |           },
 3787 |           required: ['featureId', 'phaseId', 'status'],
 3788 |           examples: [
 3789 |             {
 3790 |               featureId: "feature-123",
 3791 |               phaseId: "phase-456",
 3792 |               status: "in_progress"
 3793 |             },
 3794 |             {
 3795 |               featureId: "feature-123",
 3796 |               phaseId: "phase-456",
 3797 |               status: "completed"
 3798 |             }
 3799 |           ]
 3800 |         },
 3801 |         handler: async (params: {featureId: string, phaseId: string, status: PhaseStatus}) => {
 3802 |           const { featureId, phaseId, status } = params;
 3803 |           const feature = getFeature(featureId);
 3804 |           
 3805 |           if (!feature) {
 3806 |             return {
 3807 |               error: `Feature with ID ${featureId} not found`
 3808 |             };
 3809 |           }
 3810 |           
 3811 |           const phase = feature.phases.find(p => p.id === phaseId);
 3812 |           
 3813 |           if (!phase) {
 3814 |             return {
 3815 |               error: `Phase with ID ${phaseId} not found in feature ${feature.name}`
 3816 |             };
 3817 |           }
 3818 |           
 3819 |           // Validate the status transition
 3820 |           const validationResult = validatePhaseTransition(phase.status, status);
 3821 |           
 3822 |           if (!validationResult.valid) {
 3823 |             return {
 3824 |               error: validationResult.message
 3825 |             };
 3826 |           }
 3827 |           
 3828 |           // Update the phase status
 3829 |           const updatedPhase = updatePhaseStatus(featureId, phaseId, status);
 3830 |           
 3831 |           return {
 3832 |             success: true,
 3833 |             message: `Phase ${phase.name} status updated to ${status}`,
 3834 |             phase: updatedPhase
 3835 |           };
 3836 |         }
 3837 |       },
 3838 |       {
 3839 |         name: 'add_task',
 3840 |         description: 'Add a task to a development phase',
 3841 |         inputSchema: {
 3842 |           type: 'object',
 3843 |           properties: {
 3844 |             featureId: {
 3845 |               type: 'string',
 3846 |               description: 'ID of the feature containing the phase'
 3847 |             },
 3848 |             phaseId: {
 3849 |               type: 'string',
 3850 |               description: 'ID of the phase to add the task to'
 3851 |             },
 3852 |             description: {
 3853 |               type: 'string',
 3854 |               description: 'Description of the task'
 3855 |             }
 3856 |           },
 3857 |           required: ['featureId', 'phaseId', 'description'],
 3858 |           examples: [
 3859 |             {
 3860 |               featureId: "feature-123",
 3861 |               phaseId: "phase-456",
 3862 |               description: "Create database migration scripts"
 3863 |             },
 3864 |             {
 3865 |               featureId: "feature-123",
 3866 |               phaseId: "phase-456",
 3867 |               description: "Implement user interface components"
 3868 |             }
 3869 |           ]
 3870 |         },
 3871 |         handler: async (params: {featureId: string, phaseId: string, description: string}) => {
 3872 |           const { featureId, phaseId, description } = params;
 3873 |           const feature = getFeature(featureId);
 3874 |           
 3875 |           if (!feature) {
 3876 |             return {
 3877 |               error: `Feature with ID ${featureId} not found`
 3878 |             };
 3879 |           }
 3880 |           
 3881 |           const phase = feature.phases.find(p => p.id === phaseId);
 3882 |           
 3883 |           if (!phase) {
 3884 |             return {
 3885 |               error: `Phase with ID ${phaseId} not found in feature ${feature.name}`
 3886 |             };
 3887 |           }
 3888 |           
 3889 |           // Add the task to the phase
 3890 |           const updatedPhase = addTask(featureId, phaseId, description);
 3891 |           
 3892 |           return {
 3893 |             success: true,
 3894 |             message: `Task added to phase ${phase.name}`,
 3895 |             phase: updatedPhase
 3896 |           };
 3897 |         }
 3898 |       },
 3899 |       {
 3900 |         name: 'update_task_status',
 3901 |         description: 'Update the completion status of a task',
 3902 |         inputSchema: {
 3903 |           type: 'object',
 3904 |           properties: {
 3905 |             featureId: {
 3906 |               type: 'string',
 3907 |               description: 'ID of the feature containing the phase'
 3908 |             },
 3909 |             phaseId: {
 3910 |               type: 'string',
 3911 |               description: 'ID of the phase containing the task'
 3912 |             },
 3913 |             taskId: {
 3914 |               type: 'string',
 3915 |               description: 'ID of the task to update'
 3916 |             },
 3917 |             completed: {
 3918 |               type: 'boolean',
 3919 |               description: 'Whether the task is completed'
 3920 |             }
 3921 |           },
 3922 |           required: ['featureId', 'phaseId', 'taskId', 'completed'],
 3923 |           examples: [
 3924 |             {
 3925 |               featureId: "feature-123",
 3926 |               phaseId: "phase-456",
 3927 |               taskId: "task-789",
 3928 |               completed: true
 3929 |             },
 3930 |             {
 3931 |               featureId: "feature-123",
 3932 |               phaseId: "phase-456",
 3933 |               taskId: "task-789",
 3934 |               completed: false
 3935 |             }
 3936 |           ]
 3937 |         },
 3938 |         handler: async (params: {featureId: string, phaseId: string, taskId: string, completed: boolean}) => {
 3939 |           const { featureId, phaseId, taskId, completed } = params;
 3940 |           const feature = getFeature(featureId);
 3941 |           
 3942 |           if (!feature) {
 3943 |             return {
 3944 |               error: `Feature with ID ${featureId} not found`
 3945 |             };
 3946 |           }
 3947 |           
 3948 |           const phase = feature.phases.find(p => p.id === phaseId);
 3949 |           
 3950 |           if (!phase) {
 3951 |             return {
 3952 |               error: `Phase with ID ${phaseId} not found in feature ${feature.name}`
 3953 |             };
 3954 |           }
 3955 |           
 3956 |           const task = phase.tasks.find(t => t.id === taskId);
 3957 |           
 3958 |           if (!task) {
 3959 |             return {
 3960 |               error: `Task with ID ${taskId} not found in phase ${phase.name}`
 3961 |             };
 3962 |           }
 3963 |           
 3964 |           // Update the task status
 3965 |           const updatedTask = updateTaskStatus(featureId, phaseId, taskId, completed);
 3966 |           
 3967 |           // Check if all tasks are completed and suggest phase update if applicable
 3968 |           let message = `Task status updated to ${completed ? 'completed' : 'not completed'}`;
 3969 |           
 3970 |           // @ts-ignore - We know the task structure from our validation
 3971 |           if (completed && phase.tasks.every(t => t.id === taskId || t.completed)) {
 3972 |             // All tasks are now completed
 3973 |             message += `. All tasks in phase ${phase.name} are now completed. Consider updating the phase status to 'completed'.`;
 3974 |           }
 3975 |           
 3976 |           return {
 3977 |             success: true,
 3978 |             message,
 3979 |             task: updatedTask
 3980 |           };
 3981 |         }
 3982 |       },
 3983 |       {
 3984 |         name: 'get_next_phase_action',
 3985 |         description: 'Get guidance on what to do next in the current phase or whether to move to the next phase',
 3986 |         inputSchema: {
 3987 |           type: 'object',
 3988 |           properties: {
 3989 |             featureId: {
 3990 |               type: 'string',
 3991 |               description: 'ID of the feature'
 3992 |             }
 3993 |           },
 3994 |           required: ['featureId'],
 3995 |           examples: [
 3996 |             {
 3997 |               featureId: "feature-123"
 3998 |             }
 3999 |           ]
 4000 |         },
 4001 |         handler: async (params: {featureId: string}) => {
 4002 |           const { featureId } = params;
 4003 |           const feature = getFeature(featureId);
 4004 |           
 4005 |           if (!feature) {
 4006 |             return {
 4007 |               error: `Feature with ID ${featureId} not found`
 4008 |             };
 4009 |           }
 4010 |           
 4011 |           // Find the current active phase (first non-completed/reviewed phase)
 4012 |           // @ts-ignore - We know the phase structure from our Feature type
 4013 |           const currentPhase = feature.phases.find(p => p.status === 'pending' || p.status === 'in_progress');
 4014 |           
 4015 |           if (!currentPhase) {
 4016 |             // All phases are completed or reviewed
 4017 |             return {
 4018 |               content: [{
 4019 |                 type: "text",
 4020 |                 text: 'All phases are completed or reviewed. The feature implementation is done!'
 4021 |               }]
 4022 |             };
 4023 |           }
 4024 |           
 4025 |           // Check task completion status
 4026 |           // @ts-ignore - We know the task structure from our Phase type
 4027 |           const completedTasks = currentPhase.tasks.filter(t => t.completed);
 4028 |           // @ts-ignore - We know the task structure from our Phase type
 4029 |           const pendingTasks = currentPhase.tasks.filter(t => !t.completed);
 4030 |           
 4031 |           // Determine next action based on phase and task status
 4032 |           let message = '';
 4033 |           
 4034 |           if (currentPhase.status === 'pending') {
 4035 |             message = `Phase "${currentPhase.name}" is pending. Start working on this phase by setting its status to "in_progress".`;
 4036 |           } else if (currentPhase.status === 'in_progress') {
 4037 |             if (pendingTasks.length > 0) {
 4038 |               message = `${completedTasks.length}/${currentPhase.tasks.length} tasks are completed in phase "${currentPhase.name}". Continue working on pending tasks.`;
 4039 |             } else if (currentPhase.tasks.length === 0) {
 4040 |               message = `Phase "${currentPhase.name}" has no tasks defined. Add tasks or mark the phase as completed if appropriate.`;
 4041 |             } else {
 4042 |               // All tasks are completed
 4043 |               message = `All tasks in phase "${currentPhase.name}" are completed. Consider marking this phase as completed.`;
 4044 |             }
 4045 |           }
 4046 |           
 4047 |           return {
 4048 |             content: [{
 4049 |               type: "text",
 4050 |               text: message
 4051 |             }]
 4052 |           };
 4053 |         }
 4054 |       }
 4055 |     ]
 4056 |   };
 4057 | });
 4058 | 
 4059 | /**
 4060 |  * Handler for implementing MCP tools.
 4061 |  * Handles feature clarification, PRD generation, and more.
 4062 |  */
 4063 | server.setRequestHandler(CallToolRequestSchema, async (request) => {
 4064 |   try {
 4065 |     switch (request.params.name) {
 4066 |       case "start_feature_clarification": {
 4067 |         const featureName = String(request.params.arguments?.featureName || "");
 4068 |         const initialDescription = String(request.params.arguments?.initialDescription || "");
 4069 |         
 4070 |         // Validate inputs
 4071 |         const nameValidation = validateRequiredText(featureName, "Feature name", 2, 100);
 4072 |         if (!nameValidation.valid) {
 4073 |           return {
 4074 |             content: [{
 4075 |               type: "text",
 4076 |               text: `Error: ${nameValidation.message}`
 4077 |             }]
 4078 |           };
 4079 |         }
 4080 |         
 4081 |         // Initial description is optional, but if provided, validate its length
 4082 |         if (initialDescription && initialDescription.trim() !== "") {
 4083 |           const descValidation = validateRequiredText(initialDescription, "Initial description", 1, 5000);
 4084 |           if (!descValidation.valid) {
 4085 |             return {
 4086 |               content: [{
 4087 |                 type: "text", 
 4088 |                 text: `Error: ${descValidation.message}`
 4089 |               }]
 4090 |             };
 4091 |           }
 4092 |         }
 4093 |         
 4094 |         // Create a new feature
 4095 |         const feature = createFeatureObject(nameValidation.data, initialDescription);
 4096 |         storeFeature(feature);
 4097 |         
 4098 |         // Get the first clarification question
 4099 |         const firstQuestion = getNextClarificationQuestion(feature);
 4100 |         
 4101 |         return {
 4102 |           content: [{
 4103 |             type: "text",
 4104 |             text: `Feature ID: ${feature.id}\n\nLet's clarify your feature request. ${firstQuestion}`
 4105 |           }]
 4106 |         };
 4107 |       }
 4108 |       
 4109 |       case "provide_clarification": {
 4110 |         const featureId = String(request.params.arguments?.featureId || "");
 4111 |         const question = String(request.params.arguments?.question || "");
 4112 |         const answer = String(request.params.arguments?.answer || "");
 4113 |         
 4114 |         console.log(`\n[CLARIFICATION] Received request for feature ${featureId}\n  Question: "${question.substring(0, 50)}..."\n  Answer: "${answer.substring(0, 50)}..."`);
 4115 |         
 4116 |         // Basic validation
 4117 |         if (!featureId || !answer) {
 4118 |           console.log(`[CLARIFICATION] Missing required fields: featureId=${!!featureId}, answer=${!!answer}`);
 4119 |           return {
 4120 |             content: [{
 4121 |               type: "text",
 4122 |               text: "Error: Feature ID and answer are required"
 4123 |             }]
 4124 |           };
 4125 |         }
 4126 |         
 4127 |         // Get the feature
 4128 |         const feature = getFeature(featureId);
 4129 |         if (!feature) {
 4130 |           console.log(`[CLARIFICATION] Feature ID ${featureId} not found`);
 4131 |           return {
 4132 |             content: [{
 4133 |               type: "text",
 4134 |               text: `Error: Feature with ID ${featureId} not found`
 4135 |             }]
 4136 |           };
 4137 |         }
 4138 |         
 4139 |         console.log(`[CLARIFICATION] Found feature: ${feature.name} with ${feature.clarificationResponses.length} existing responses`);
 4140 |         
 4141 |         // Add the clarification response to the feature
 4142 |         feature.clarificationResponses.push({
 4143 |           question,
 4144 |           answer,
 4145 |           timestamp: new Date()
 4146 |         });
 4147 |         
 4148 |         console.log(`[CLARIFICATION] Added response, now has ${feature.clarificationResponses.length} responses`);
 4149 |         
 4150 |         // Save the feature with the updated clarification response
 4151 |         updateFeature(featureId, feature);
 4152 |         
 4153 |         // Determine which question to ask next
 4154 |         const nextQuestionIndex = feature.clarificationResponses.length;
 4155 |         
 4156 |         console.log(`[CLARIFICATION] Next question index would be: ${nextQuestionIndex}`);
 4157 |         console.log(`[CLARIFICATION] Total questions available: ${CLARIFICATION_QUESTIONS.length}`);
 4158 |         
 4159 |         if (nextQuestionIndex < CLARIFICATION_QUESTIONS.length) {
 4160 |           // We have more questions to ask
 4161 |           const nextQuestion = CLARIFICATION_QUESTIONS[nextQuestionIndex];
 4162 |           console.log(`[CLARIFICATION] Returning next question: "${nextQuestion.substring(0, 50)}..."`);
 4163 |           return {
 4164 |             content: [{
 4165 |               type: "text",
 4166 |               text: `Response recorded. ${nextQuestion}`
 4167 |             }]
 4168 |           };
 4169 |         } else {
 4170 |           // All questions answered
 4171 |           console.log(`[CLARIFICATION] All questions answered`);
 4172 |           return {
 4173 |             content: [{
 4174 |               type: "text",
 4175 |               text: "All clarification questions have been answered. You can now generate a PRD for this feature."
 4176 |             }]
 4177 |           };
 4178 |         }
 4179 |       }
 4180 |       
 4181 |       case "generate_prd": {
 4182 |         const featureId = String(request.params.arguments?.featureId || "");
 4183 |         
 4184 |         // Validate feature ID
 4185 |         const featureResult = validateFeatureId(featureId);
 4186 |         if (!featureResult.valid) {
 4187 |           return {
 4188 |             content: [{
 4189 |               type: "text",
 4190 |               text: `Error: ${featureResult.message}`
 4191 |             }]
 4192 |           };
 4193 |         }
 4194 |         
 4195 |         const feature = featureResult.data;
 4196 |         
 4197 |         // Check if clarifications are complete
 4198 |         if (!isClarificationComplete(feature)) {
 4199 |           return {
 4200 |             content: [{
 4201 |               type: "text",
 4202 |               text: "Error: Please complete all clarification questions before generating a PRD."
 4203 |             }]
 4204 |           };
 4205 |         }
 4206 |         
 4207 |         // Generate PRD and implementation plan
 4208 |         const prdDoc = generatePRD(feature);
 4209 |         const implementationPlan = generateImplementationPlan(feature);
 4210 |         
 4211 |         // Store the documents
 4212 |         feature.prdDoc = prdDoc;
 4213 |         feature.implementationPlan = implementationPlan;
 4214 |         
 4215 |         return {
 4216 |           content: [{
 4217 |             type: "text",
 4218 |             text: `PRD and Implementation Plan generated for feature ${feature.name}. You can view them using the resource URIs: feature://${feature.id}/prd and feature://${feature.id}/implementation`
 4219 |           }]
 4220 |         };
 4221 |       }
 4222 |       
 4223 |       case "create_phase": {
 4224 |         const featureId = String(request.params.arguments?.featureId || "");
 4225 |         const phaseName = String(request.params.arguments?.name || "");
 4226 |         const phaseDescription = String(request.params.arguments?.description || "");
 4227 |         const tasksJson = String(request.params.arguments?.tasks || "[]");
 4228 |         
 4229 |         // Validate feature ID
 4230 |         const featureResult = validateFeatureId(featureId);
 4231 |         if (!featureResult.valid) {
 4232 |           return {
 4233 |             content: [{
 4234 |               type: "text",
 4235 |               text: `Error: ${featureResult.message}`
 4236 |             }]
 4237 |           };
 4238 |         }
 4239 |         
 4240 |         // Validate phase name
 4241 |         const nameValidation = validateRequiredText(phaseName, "Phase name", 2, 100);
 4242 |         if (!nameValidation.valid) {
 4243 |           return {
 4244 |             content: [{
 4245 |               type: "text",
 4246 |               text: `Error: ${nameValidation.message}`
 4247 |             }]
 4248 |           };
 4249 |         }
 4250 |         
 4251 |         // Validate phase description (optional but if provided, validate)
 4252 |         if (phaseDescription && phaseDescription.trim() !== "") {
 4253 |           const descValidation = validateRequiredText(phaseDescription, "Phase description", 5, 1000);
 4254 |           if (!descValidation.valid) {
 4255 |             return {
 4256 |               content: [{
 4257 |                 type: "text",
 4258 |                 text: `Error: ${descValidation.message}`
 4259 |               }]
 4260 |             };
 4261 |           }
 4262 |         }
 4263 |         
 4264 |         // Parse and validate tasks
 4265 |         let tasks = [];
 4266 |         try {
 4267 |           tasks = JSON.parse(tasksJson);
 4268 |           if (!Array.isArray(tasks)) {
 4269 |             return {
 4270 |               content: [{
 4271 |                 type: "text",
 4272 |                 text: "Error: Tasks must be a valid JSON array of task descriptions"
 4273 |               }]
 4274 |             };
 4275 |           }
 4276 |           
 4277 |           // Validate each task description
 4278 |           for (let i = 0; i < tasks.length; i++) {
 4279 |             const taskDesc = tasks[i];
 4280 |             if (typeof taskDesc !== 'string' || taskDesc.trim().length < 3) {
 4281 |               return {
 4282 |                 content: [{
 4283 |                   type: "text",
 4284 |                   text: `Error: Task at index ${i} must be a string with at least 3 characters`
 4285 |                 }]
 4286 |               };
 4287 |             }
 4288 |           }
 4289 |         } catch (e) {
 4290 |           return {
 4291 |             content: [{
 4292 |               type: "text",
 4293 |               text: "Error: Could not parse tasks JSON. Please provide a valid JSON array."
 4294 |             }]
 4295 |           };
 4296 |         }
 4297 |         
 4298 |         const feature = featureResult.data;
 4299 |         
 4300 |         // Create the phase
 4301 |         const phase = createPhase(featureId, nameValidation.data, phaseDescription);
 4302 |         
 4303 |         if (!phase) {
 4304 |           return {
 4305 |             content: [{
 4306 |               type: "text",
 4307 |               text: `Error: Failed to create phase for feature ${feature.name}`
 4308 |             }]
 4309 |           };
 4310 |         }
 4311 |         
 4312 |         // Add tasks if provided
 4313 |         if (tasks.length > 0) {
 4314 |           tasks.forEach(taskDesc => {
 4315 |             addTask(featureId, phase.id, taskDesc);
 4316 |           });
 4317 |         }
 4318 |         
 4319 |         return {
 4320 |           content: [{
 4321 |             type: "text",
 4322 |             text: `Phase "${phaseName}" created with ID: ${phase.id}`
 4323 |           }]
 4324 |         };
 4325 |       }
 4326 |       
 4327 |       case "update_phase_status": {
 4328 |         const featureId = String(request.params.arguments?.featureId || "");
 4329 |         const phaseId = String(request.params.arguments?.phaseId || "");
 4330 |         const status = String(request.params.arguments?.status || "");
 4331 |         
 4332 |         // Validate feature and phase
 4333 |         const validationResult = validateFeaturePhaseTask(featureId, phaseId);
 4334 |         if (!validationResult.valid) {
 4335 |           return {
 4336 |             content: [{
 4337 |               type: "text",
 4338 |               text: `Error: ${validationResult.message}`
 4339 |             }]
 4340 |           };
 4341 |         }
 4342 |         
 4343 |         // Validate status
 4344 |         const statusValidation = validatePhaseStatusValue(status);
 4345 |         if (!statusValidation.valid) {
 4346 |           return {
 4347 |             content: [{
 4348 |               type: "text",
 4349 |               text: `Error: ${statusValidation.message}`
 4350 |             }]
 4351 |           };
 4352 |         }
 4353 |         
 4354 |         const { feature, phase } = validationResult.data;
 4355 |         
 4356 |         // Update the phase status
 4357 |         const updatedPhase = updatePhaseStatus(featureId, phaseId, statusValidation.data);
 4358 |         
 4359 |         return {
 4360 |           content: [{
 4361 |             type: "text",
 4362 |             text: `Phase status updated to "${status}"`
 4363 |           }]
 4364 |         };
 4365 |       }
 4366 |       
 4367 |       case "add_task": {
 4368 |         const featureId = String(request.params.arguments?.featureId || "");
 4369 |         const phaseId = String(request.params.arguments?.phaseId || "");
 4370 |         const taskDescription = String(request.params.arguments?.description || "");
 4371 |         
 4372 |         // Validate feature and phase
 4373 |         const validationResult = validateFeaturePhaseTask(featureId, phaseId);
 4374 |         if (!validationResult.valid) {
 4375 |           return {
 4376 |             content: [{
 4377 |               type: "text",
 4378 |               text: `Error: ${validationResult.message}`
 4379 |             }]
 4380 |           };
 4381 |         }
 4382 |         
 4383 |         // Validate task description
 4384 |         const descValidation = validateRequiredText(taskDescription, "Task description", 3, 500);
 4385 |         if (!descValidation.valid) {
 4386 |           return {
 4387 |             content: [{
 4388 |               type: "text",
 4389 |               text: `Error: ${descValidation.message}`
 4390 |             }]
 4391 |           };
 4392 |         }
 4393 |         
 4394 |         const { feature, phase } = validationResult.data;
 4395 |         
 4396 |         // Add the task
 4397 |         const taskId = addTask(featureId, phaseId, descValidation.data);
 4398 |         
 4399 |         return {
 4400 |           content: [{
 4401 |             type: "text",
 4402 |             text: `Task added to phase "${phase.name}" with ID: ${taskId}`
 4403 |           }]
 4404 |         };
 4405 |       }
 4406 |       
 4407 |       case "update_task_status": {
 4408 |         const featureId = String(request.params.arguments?.featureId || "");
 4409 |         const phaseId = String(request.params.arguments?.phaseId || "");
 4410 |         const taskId = String(request.params.arguments?.taskId || "");
 4411 |         const completed = Boolean(request.params.arguments?.completed);
 4412 |         
 4413 |         // Validate feature, phase and task
 4414 |         const validationResult = validateFeaturePhaseTask(featureId, phaseId, taskId);
 4415 |         if (!validationResult.valid) {
 4416 |           return {
 4417 |             content: [{
 4418 |               type: "text",
 4419 |               text: `Error: ${validationResult.message}`
 4420 |             }]
 4421 |           };
 4422 |         }
 4423 |         
 4424 |         const { feature, phase, task } = validationResult.data;
 4425 |         
 4426 |         // Update the task status
 4427 |         const updatedTask = updateTaskStatus(featureId, phaseId, taskId, completed);
 4428 |         
 4429 |         // Check if all tasks are completed and suggest phase update if applicable
 4430 |         let message = `Task status updated to ${completed ? 'completed' : 'not completed'}`;
 4431 |         
 4432 |         // @ts-ignore - We know the task structure from our validation
 4433 |         if (completed && phase.tasks.every(t => t.id === taskId || t.completed)) {
 4434 |           // All tasks are now completed
 4435 |           message += `. All tasks in phase ${phase.name} are now completed. Consider updating the phase status to 'completed'.`;
 4436 |         }
 4437 |         
 4438 |         return {
 4439 |           content: [{
 4440 |             type: "text",
 4441 |             text: message
 4442 |           }]
 4443 |         };
 4444 |       }
 4445 |       
 4446 |       case "get_next_phase_action": {
 4447 |         const featureId = String(request.params.arguments?.featureId || "");
 4448 |         
 4449 |         // Validate feature ID
 4450 |         const featureResult = validateFeatureId(featureId);
 4451 |         if (!featureResult.valid) {
 4452 |           return {
 4453 |             content: [{
 4454 |               type: "text",
 4455 |               text: `Error: ${featureResult.message}`
 4456 |             }]
 4457 |           };
 4458 |         }
 4459 |         
 4460 |         const feature = featureResult.data;
 4461 |         
 4462 |         // Find the current active phase (first non-completed/reviewed phase)
 4463 |         // @ts-ignore - We know the phase structure from our Feature type
 4464 |         const currentPhase = feature.phases.find(p => p.status === 'pending' || p.status === 'in_progress');
 4465 |         
 4466 |         if (!currentPhase) {
 4467 |           // All phases are completed or reviewed
 4468 |           return {
 4469 |             content: [{
 4470 |               type: "text",
 4471 |               text: 'All phases are completed or reviewed. The feature implementation is done!'
 4472 |             }]
 4473 |           };
 4474 |         }
 4475 |         
 4476 |         // Check task completion status
 4477 |         // @ts-ignore - We know the task structure from our Phase type
 4478 |         const completedTasks = currentPhase.tasks.filter(t => t.completed);
 4479 |         // @ts-ignore - We know the task structure from our Phase type
 4480 |         const pendingTasks = currentPhase.tasks.filter(t => !t.completed);
 4481 |         
 4482 |         // Determine next action based on phase and task status
 4483 |         let message = '';
 4484 |         
 4485 |         if (currentPhase.status === 'pending') {
 4486 |           message = `Phase "${currentPhase.name}" is pending. Start working on this phase by setting its status to "in_progress".`;
 4487 |         } else if (currentPhase.status === 'in_progress') {
 4488 |           if (pendingTasks.length > 0) {
 4489 |             message = `${completedTasks.length}/${currentPhase.tasks.length} tasks are completed in phase "${currentPhase.name}". Continue working on pending tasks.`;
 4490 |           } else if (currentPhase.tasks.length === 0) {
 4491 |             message = `Phase "${currentPhase.name}" has no tasks defined. Add tasks or mark the phase as completed if appropriate.`;
 4492 |           } else {
 4493 |             // All tasks are completed
 4494 |             message = `All tasks in phase "${currentPhase.name}" are completed. Consider marking this phase as completed.`;
 4495 |           }
 4496 |         }
 4497 |         
 4498 |         return {
 4499 |           content: [{
 4500 |             type: "text",
 4501 |             text: message
 4502 |           }]
 4503 |         };
 4504 |       }
 4505 |       
 4506 |       default:
 4507 |         return {
 4508 |           content: [{
 4509 |             type: "text",
 4510 |             text: `Error: Unknown tool "${request.params.name}"`
 4511 |           }]
 4512 |         };
 4513 |     }
 4514 |   } catch (error: any) {
 4515 |     console.error('Error executing tool:', error);
 4516 |     return {
 4517 |       content: [{
 4518 |         type: "text",
 4519 |         text: `An unexpected error occurred: ${error.message || 'Unknown error'}`
 4520 |       }]
 4521 |     };
 4522 |   }
 4523 | });
 4524 | 
 4525 | /**
 4526 |  * Handler that lists available prompts.
 4527 |  */
 4528 | server.setRequestHandler(ListPromptsRequestSchema, async () => {
 4529 |   return {
 4530 |     prompts: [
 4531 |       {
 4532 |         name: "clarify_feature",
 4533 |         description: "Guide to clarify a feature request through questioning"
 4534 |       }
 4535 |     ]
 4536 |   };
 4537 | });
 4538 | 
 4539 | /**
 4540 |  * Handler for the clarify_feature prompt.
 4541 |  * Returns a prompt that guides feature clarification.
 4542 |  */
 4543 | server.setRequestHandler(GetPromptRequestSchema, async (request) => {
 4544 |   if (request.params.name === "clarify_feature") {
 4545 |     return {
 4546 |       messages: [
 4547 |         {
 4548 |           role: "user",
 4549 |           content: {
 4550 |             type: "text",
 4551 |             text: "Help me clarify this feature request by asking questions about:"
 4552 |           }
 4553 |         },
 4554 |         {
 4555 |           role: "user",
 4556 |           content: {
 4557 |             type: "text",
 4558 |             text: "1. The specific problem it solves\n2. The target users\n3. Key requirements\n4. Success criteria\n5. Technical constraints\n\nAsk one question at a time, analyze the response, then proceed to the next most relevant question."
 4559 |           }
 4560 |         }
 4561 |       ]
 4562 |     };
 4563 |   }
 4564 |   
 4565 |   throw new Error("Unknown prompt");
 4566 | });
 4567 | 
 4568 | /**
 4569 |  * Start the server using stdio transport.
 4570 |  * This allows the server to communicate via standard input/output streams.
 4571 |  */
 4572 | async function main() {
 4573 |   console.error("Starting Vibe-Coder MCP Server...");
 4574 |   
 4575 |   const transport = new StdioServerTransport();
 4576 |   await server.connect(transport);
 4577 | }
 4578 | 
 4579 | main().catch((error) => {
 4580 |   console.error("Server error:", error);
 4581 |   process.exit(1);
 4582 | });
 4583 | 
 4584 | ================
 4585 | File: src/mcp-server.ts
 4586 | ================
 4587 | #!/usr/bin/env node
 4588 | 
 4589 | /**
 4590 |  * @file Vibe-Coder MCP Server
 4591 |  * @version 0.3.0
 4592 |  * @status STABLE - DO NOT MODIFY WITHOUT TESTS
 4593 |  * @lastModified 2023-03-23
 4594 |  * 
 4595 |  * This MCP server implements a structured development workflow that helps
 4596 |  * LLM-based coders build features in an organized, clean, and safe manner.
 4597 |  * 
 4598 |  * IMPORTANT:
 4599 |  * - Test any modifications thoroughly
 4600 |  * - Maintain backward compatibility
 4601 |  * 
 4602 |  * Functionality:
 4603 |  * - Feature request clarification through iterative questioning
 4604 |  * - PRD and implementation plan generation
 4605 |  * - Phased development with tasks and status tracking
 4606 |  */
 4607 | 
 4608 | import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
 4609 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
 4610 | import { z } from "zod";
 4611 | 
 4612 | // Import core modules
 4613 | import { Feature, Phase, Task, ClarificationResponse, PhaseStatus } from './types.js';
 4614 | import { getFeature, updateFeature, listFeatures } from './storage.js';
 4615 | import { 
 4616 |   getNextClarificationQuestion, 
 4617 |   addClarificationResponse,
 4618 |   formatClarificationResponses,
 4619 |   isClarificationComplete
 4620 | } from './clarification.js';
 4621 | import { generatePRD, generateImplementationPlan } from './documentation.js';
 4622 | import { createFeatureObject, generateFeatureProgressSummary, createPhaseObject, createTaskObject, now } from './utils.js';
 4623 | 
 4624 | /**
 4625 |  * Create an MCP server
 4626 |  */
 4627 | const server = new McpServer({
 4628 |   name: "Vibe-Coder",
 4629 |   version: "0.3.0"
 4630 | });
 4631 | 
 4632 | // --------- Helper Functions ---------
 4633 | 
 4634 | /**
 4635 |  * Create a new phase for a feature directly
 4636 |  */
 4637 | function createPhaseDirectly(feature: Feature, name: string, description: string): Phase {
 4638 |   const newPhase = createPhaseObject(name, description);
 4639 |   feature.phases.push(newPhase);
 4640 |   feature.updatedAt = new Date();
 4641 |   return newPhase;
 4642 | }
 4643 | 
 4644 | /**
 4645 |  * Update phase status directly
 4646 |  */
 4647 | function updatePhaseStatusDirectly(feature: Feature, phaseId: string, status: PhaseStatus): void {
 4648 |   const phase = feature.phases.find(p => p.id === phaseId);
 4649 |   if (!phase) {
 4650 |     throw new Error(`Phase ${phaseId} not found`);
 4651 |   }
 4652 |   
 4653 |   phase.status = status;
 4654 |   phase.updatedAt = now();
 4655 |   feature.updatedAt = now();
 4656 | }
 4657 | 
 4658 | /**
 4659 |  * Add task directly
 4660 |  */
 4661 | function addTaskDirectly(feature: Feature, phaseId: string, description: string): Task {
 4662 |   const phase = feature.phases.find(p => p.id === phaseId);
 4663 |   if (!phase) {
 4664 |     throw new Error(`Phase ${phaseId} not found`);
 4665 |   }
 4666 |   
 4667 |   const newTask = createTaskObject(description);
 4668 |   
 4669 |   // Convert task ID to string to ensure it's not an object
 4670 |   if (typeof newTask.id !== 'string') {
 4671 |     newTask.id = String(newTask.id);
 4672 |   }
 4673 |   
 4674 |   phase.tasks.push(newTask);
 4675 |   phase.updatedAt = now();
 4676 |   feature.updatedAt = now();
 4677 |   return newTask;
 4678 | }
 4679 | 
 4680 | /**
 4681 |  * Update task status directly
 4682 |  */
 4683 | function updateTaskStatusDirectly(feature: Feature, phaseId: string, taskId: string, completed: boolean): void {
 4684 |   const phase = feature.phases.find(p => p.id === phaseId);
 4685 |   if (!phase) {
 4686 |     throw new Error(`Phase ${phaseId} not found`);
 4687 |   }
 4688 |   
 4689 |   const task = phase.tasks.find(t => t.id === taskId);
 4690 |   if (!task) {
 4691 |     throw new Error(`Task ${taskId} not found`);
 4692 |   }
 4693 |   
 4694 |   task.completed = completed;
 4695 |   task.updatedAt = now();
 4696 |   phase.updatedAt = now();
 4697 |   feature.updatedAt = now();
 4698 | }
 4699 | 
 4700 | // --------- Register Resources ---------
 4701 | 
 4702 | // Features list resource
 4703 | server.resource(
 4704 |   "features-list",
 4705 |   "features://list",
 4706 |   async (uri) => ({
 4707 |     contents: [{
 4708 |       uri: uri.href,
 4709 |       text: listFeatures().map(f => `${f.id}: ${f.name}`).join("\n")
 4710 |     }]
 4711 |   })
 4712 | );
 4713 | 
 4714 | // Features status resource
 4715 | server.resource(
 4716 |   "features-status",
 4717 |   "features://status",
 4718 |   async (uri) => {
 4719 |     const features = listFeatures();
 4720 |     
 4721 |     if (features.length === 0) {
 4722 |       return {
 4723 |         contents: [{
 4724 |           uri: uri.href,
 4725 |           text: "# Project Status\n\nNo features have been created yet."
 4726 |         }]
 4727 |       };
 4728 |     }
 4729 |     
 4730 |     const featuresStatus = features.map(feature => {
 4731 |       const totalPhases = feature.phases.length;
 4732 |       const completedPhases = feature.phases.filter(p => p.status === 'completed' || p.status === 'reviewed').length;
 4733 |       const totalTasks = feature.phases.reduce((acc, phase) => acc + phase.tasks.length, 0);
 4734 |       const completedTasks = feature.phases.reduce(
 4735 |         (acc, phase) => acc + phase.tasks.filter(t => t.completed).length, 0
 4736 |       );
 4737 |       
 4738 |       return `## ${feature.name}
 4739 | - ID: ${feature.id}
 4740 | - Status: ${completedPhases === totalPhases && totalPhases > 0 ? 'Completed' : 'In Progress'}
 4741 | - Phases: ${completedPhases}/${totalPhases} completed
 4742 | - Tasks: ${completedTasks}/${totalTasks} completed
 4743 | - [View Details](feature://${feature.id}/progress)
 4744 | `;
 4745 |     }).join('\n');
 4746 |     
 4747 |     return {
 4748 |       contents: [{
 4749 |         uri: uri.href,
 4750 |         text: `# Project Status\n\n${featuresStatus}`
 4751 |       }]
 4752 |     };
 4753 |   }
 4754 | );
 4755 | 
 4756 | // Feature detail resource with parameter
 4757 | server.resource(
 4758 |   "feature-detail",
 4759 |   new ResourceTemplate("feature://{featureId}", { list: undefined }),
 4760 |   async (uri, { featureId }) => {
 4761 |     const feature = getFeature(featureId as string);
 4762 |     
 4763 |     if (!feature) {
 4764 |       throw new Error(`Feature ${featureId} not found`);
 4765 |     }
 4766 |     
 4767 |     const timestamp = feature.updatedAt.toISOString();
 4768 |     const clarifications = formatClarificationResponses(feature.clarificationResponses);
 4769 |     const phasesText = feature.phases.map(p => 
 4770 |       `- ${p.name} (${p.status}): ${p.tasks.filter(t => t.completed).length}/${p.tasks.length} tasks completed`
 4771 |     ).join('\n');
 4772 |     
 4773 |     const featureDetails = `
 4774 | Feature: ${feature.name}
 4775 | ID: ${feature.id}
 4776 | Description: ${feature.description}
 4777 | Last Updated: ${timestamp}
 4778 | 
 4779 | Clarification Responses:
 4780 | ${clarifications}
 4781 | 
 4782 | Phases (${feature.phases.length}):
 4783 | ${phasesText}
 4784 | `;
 4785 |     
 4786 |     return {
 4787 |       contents: [{
 4788 |         uri: uri.href,
 4789 |         text: featureDetails
 4790 |       }]
 4791 |     };
 4792 |   }
 4793 | );
 4794 | 
 4795 | // Feature progress resource
 4796 | server.resource(
 4797 |   "feature-progress",
 4798 |   new ResourceTemplate("feature://{featureId}/progress", { list: undefined }),
 4799 |   async (uri, { featureId }) => {
 4800 |     const feature = getFeature(featureId as string);
 4801 |     
 4802 |     if (!feature) {
 4803 |       throw new Error(`Feature ${featureId} not found`);
 4804 |     }
 4805 |     
 4806 |     const progressReport = generateFeatureProgressSummary(feature);
 4807 |     
 4808 |     return {
 4809 |       contents: [{
 4810 |         uri: uri.href,
 4811 |         text: progressReport
 4812 |       }]
 4813 |     };
 4814 |   }
 4815 | );
 4816 | 
 4817 | // Feature PRD resource
 4818 | server.resource(
 4819 |   "feature-prd",
 4820 |   new ResourceTemplate("feature://{featureId}/prd", { list: undefined }),
 4821 |   async (uri, { featureId }) => {
 4822 |     const feature = getFeature(featureId as string);
 4823 |     
 4824 |     if (!feature) {
 4825 |       throw new Error(`Feature ${featureId} not found`);
 4826 |     }
 4827 |     
 4828 |     if (!isClarificationComplete(feature)) {
 4829 |       return {
 4830 |         contents: [{
 4831 |           uri: uri.href,
 4832 |           text: "# PRD Not Available\n\nThe clarification process is not complete. Please answer all clarification questions first."
 4833 |         }]
 4834 |       };
 4835 |     }
 4836 |     
 4837 |     const prd = generatePRD(feature);
 4838 |     
 4839 |     return {
 4840 |       contents: [{
 4841 |         uri: uri.href,
 4842 |         text: prd
 4843 |       }]
 4844 |     };
 4845 |   }
 4846 | );
 4847 | 
 4848 | // Feature implementation plan resource
 4849 | server.resource(
 4850 |   "feature-implementation-plan",
 4851 |   new ResourceTemplate("feature://{featureId}/implementation", { list: undefined }),
 4852 |   async (uri, { featureId }) => {
 4853 |     const feature = getFeature(featureId as string);
 4854 |     
 4855 |     if (!feature) {
 4856 |       throw new Error(`Feature ${featureId} not found`);
 4857 |     }
 4858 |     
 4859 |     if (!isClarificationComplete(feature)) {
 4860 |       return {
 4861 |         contents: [{
 4862 |           uri: uri.href,
 4863 |           text: "# Implementation Plan Not Available\n\nThe clarification process is not complete. Please answer all clarification questions first."
 4864 |         }]
 4865 |       };
 4866 |     }
 4867 |     
 4868 |     const implementationPlan = generateImplementationPlan(feature);
 4869 |     
 4870 |     return {
 4871 |       contents: [{
 4872 |         uri: uri.href,
 4873 |         text: implementationPlan
 4874 |       }]
 4875 |     };
 4876 |   }
 4877 | );
 4878 | 
 4879 | // --------- Register Tools ---------
 4880 | 
 4881 | // Start feature clarification tool
 4882 | server.tool(
 4883 |   "start_feature_clarification",
 4884 |   { 
 4885 |     featureName: z.string().min(2).max(100),
 4886 |     initialDescription: z.string().optional().default("")
 4887 |   },
 4888 |   async ({ featureName, initialDescription }) => {
 4889 |     // Create a new feature
 4890 |     const feature = createFeatureObject(featureName, initialDescription);
 4891 |     updateFeature(feature.id, feature);
 4892 |     
 4893 |     // Get the first clarification question
 4894 |     const firstQuestion = getNextClarificationQuestion(feature);
 4895 |     
 4896 |     return {
 4897 |       content: [{
 4898 |         type: "text",
 4899 |         text: `Feature ID: ${feature.id}\n\nLet's clarify your feature request. ${firstQuestion}`
 4900 |       }]
 4901 |     };
 4902 |   }
 4903 | );
 4904 | 
 4905 | // Provide clarification tool
 4906 | server.tool(
 4907 |   "provide_clarification",
 4908 |   {
 4909 |     featureId: z.string().min(1),
 4910 |     question: z.string().min(1),
 4911 |     answer: z.string().min(1)
 4912 |   },
 4913 |   async ({ featureId, question, answer }) => {
 4914 |     // Get the feature
 4915 |     const feature = getFeature(featureId);
 4916 |     if (!feature) {
 4917 |       throw new Error(`Feature ${featureId} not found`);
 4918 |     }
 4919 |     
 4920 |     // Add the clarification response to the feature
 4921 |     feature.clarificationResponses.push({
 4922 |       question,
 4923 |       answer,
 4924 |       timestamp: new Date()
 4925 |     });
 4926 |     
 4927 |     // Save the feature with the updated clarification response
 4928 |     updateFeature(featureId, feature);
 4929 |     
 4930 |     // Get the next question or indicate all questions are answered
 4931 |     const nextQuestion = getNextClarificationQuestion(feature);
 4932 |     
 4933 |     if (nextQuestion) {
 4934 |       return {
 4935 |         content: [{
 4936 |           type: "text",
 4937 |           text: `Response recorded. ${nextQuestion}`
 4938 |         }]
 4939 |       };
 4940 |     } else {
 4941 |       // All questions answered
 4942 |       return {
 4943 |         content: [{
 4944 |           type: "text",
 4945 |           text: "All clarification questions have been answered. You can now generate a PRD for this feature."
 4946 |         }]
 4947 |       };
 4948 |     }
 4949 |   }
 4950 | );
 4951 | 
 4952 | // Generate PRD tool
 4953 | server.tool(
 4954 |   "generate_prd",
 4955 |   {
 4956 |     featureId: z.string().min(1)
 4957 |   },
 4958 |   async ({ featureId }) => {
 4959 |     const feature = getFeature(featureId);
 4960 |     if (!feature) {
 4961 |       throw new Error(`Feature ${featureId} not found`);
 4962 |     }
 4963 |     
 4964 |     if (!isClarificationComplete(feature)) {
 4965 |       throw new Error("Clarification process not complete. Please answer all clarification questions.");
 4966 |     }
 4967 |     
 4968 |     const prd = generatePRD(feature);
 4969 |     feature.prd = prd;
 4970 |     updateFeature(featureId, feature);
 4971 |     
 4972 |     return {
 4973 |       content: [{
 4974 |         type: "text",
 4975 |         text: `PRD generated successfully for "${feature.name}". You can view it at feature://${featureId}/prd`
 4976 |       }]
 4977 |     };
 4978 |   }
 4979 | );
 4980 | 
 4981 | // Create phase tool
 4982 | server.tool(
 4983 |   "create_phase",
 4984 |   {
 4985 |     featureId: z.string().min(1),
 4986 |     name: z.string().min(1),
 4987 |     description: z.string().min(1)
 4988 |   },
 4989 |   async ({ featureId, name, description }) => {
 4990 |     const feature = getFeature(featureId);
 4991 |     if (!feature) {
 4992 |       throw new Error(`Feature ${featureId} not found`);
 4993 |     }
 4994 |     
 4995 |     const phase = createPhaseDirectly(feature, name, description);
 4996 |     updateFeature(featureId, feature);
 4997 |     
 4998 |     return {
 4999 |       content: [{
 5000 |         type: "text",
 5001 |         text: `Created phase "${name}" with ID ${phase.id} for feature "${feature.name}"`
 5002 |       }]
 5003 |     };
 5004 |   }
 5005 | );
 5006 | 
 5007 | // Update phase status tool
 5008 | server.tool(
 5009 |   "update_phase_status",
 5010 |   {
 5011 |     featureId: z.string().min(1),
 5012 |     phaseId: z.string().min(1),
 5013 |     status: z.enum(["pending", "in_progress", "completed", "reviewed"])
 5014 |   },
 5015 |   async ({ featureId, phaseId, status }) => {
 5016 |     const feature = getFeature(featureId);
 5017 |     if (!feature) {
 5018 |       throw new Error(`Feature ${featureId} not found`);
 5019 |     }
 5020 |     
 5021 |     const phase = feature.phases.find(p => p.id === phaseId);
 5022 |     if (!phase) {
 5023 |       throw new Error(`Phase ${phaseId} not found in feature ${featureId}`);
 5024 |     }
 5025 |     
 5026 |     const oldStatus = phase.status;
 5027 |     updatePhaseStatusDirectly(feature, phaseId, status);
 5028 |     updateFeature(featureId, feature);
 5029 |     
 5030 |     return {
 5031 |       content: [{
 5032 |         type: "text",
 5033 |         text: `Updated phase "${phase.name}" status from "${oldStatus}" to "${status}"`
 5034 |       }]
 5035 |     };
 5036 |   }
 5037 | );
 5038 | 
 5039 | // Add task tool
 5040 | server.tool(
 5041 |   "add_task",
 5042 |   {
 5043 |     featureId: z.string().min(1),
 5044 |     phaseId: z.string().min(1),
 5045 |     description: z.string().min(1)
 5046 |   },
 5047 |   async ({ featureId, phaseId, description }) => {
 5048 |     const feature = getFeature(featureId);
 5049 |     if (!feature) {
 5050 |       throw new Error(`Feature ${featureId} not found`);
 5051 |     }
 5052 |     
 5053 |     const phase = feature.phases.find(p => p.id === phaseId);
 5054 |     if (!phase) {
 5055 |       throw new Error(`Phase ${phaseId} not found in feature ${featureId}`);
 5056 |     }
 5057 |     
 5058 |     const task = addTaskDirectly(feature, phaseId, description);
 5059 |     updateFeature(featureId, feature);
 5060 |     
 5061 |     // Debug log
 5062 |     console.error(`DEBUG: Task created with ID: ${task.id}, type: ${typeof task.id}`);
 5063 |     console.error(`DEBUG: Task object: ${JSON.stringify(task)}`);
 5064 |     
 5065 |     // Ensure task.id is explicitly converted to string and check if it's an object
 5066 |     let taskId: string;
 5067 |     
 5068 |     if (typeof task.id === 'object') {
 5069 |       taskId = JSON.stringify(task.id);
 5070 |     } else {
 5071 |       taskId = String(task.id);
 5072 |     }
 5073 |     
 5074 |     return {
 5075 |       content: [{
 5076 |         type: "text",
 5077 |         text: `Added task "${description.substring(0, 30)}${description.length > 30 ? '...' : ''}" with ID: ${taskId} to phase "${phase.name}"`
 5078 |       }]
 5079 |     };
 5080 |   }
 5081 | );
 5082 | 
 5083 | // Update task status tool
 5084 | server.tool(
 5085 |   "update_task_status",
 5086 |   {
 5087 |     featureId: z.string().min(1),
 5088 |     phaseId: z.string().min(1),
 5089 |     taskId: z.string().min(1),
 5090 |     completed: z.boolean()
 5091 |   },
 5092 |   async ({ featureId, phaseId, taskId, completed }) => {
 5093 |     const feature = getFeature(featureId);
 5094 |     if (!feature) {
 5095 |       throw new Error(`Feature ${featureId} not found`);
 5096 |     }
 5097 |     
 5098 |     const phase = feature.phases.find(p => p.id === phaseId);
 5099 |     if (!phase) {
 5100 |       throw new Error(`Phase ${phaseId} not found in feature ${featureId}`);
 5101 |     }
 5102 |     
 5103 |     const task = phase.tasks.find(t => t.id === taskId);
 5104 |     if (!task) {
 5105 |       throw new Error(`Task ${taskId} not found in phase ${phaseId}`);
 5106 |     }
 5107 |     
 5108 |     updateTaskStatusDirectly(feature, phaseId, taskId, completed);
 5109 |     updateFeature(featureId, feature);
 5110 |     
 5111 |     return {
 5112 |       content: [{
 5113 |         type: "text",
 5114 |         text: `Updated task "${task.description.substring(0, 30)}${task.description.length > 30 ? '...' : ''}" status to ${completed ? 'completed' : 'not completed'}`
 5115 |       }]
 5116 |     };
 5117 |   }
 5118 | );
 5119 | 
 5120 | // Get next phase action tool
 5121 | server.tool(
 5122 |   "get_next_phase_action",
 5123 |   {
 5124 |     featureId: z.string().min(1)
 5125 |   },
 5126 |   async ({ featureId }) => {
 5127 |     const feature = getFeature(featureId);
 5128 |     if (!feature) {
 5129 |       throw new Error(`Feature ${featureId} not found`);
 5130 |     }
 5131 |     
 5132 |     // Check if we need implementation plan first
 5133 |     if (!feature.implementationPlan) {
 5134 |       return {
 5135 |         content: [{
 5136 |           type: "text",
 5137 |           text: "You should generate an implementation plan before creating phases."
 5138 |         }]
 5139 |       };
 5140 |     }
 5141 |     
 5142 |     // If no phases, suggest creating first phase
 5143 |     if (feature.phases.length === 0) {
 5144 |       return {
 5145 |         content: [{
 5146 |           type: "text",
 5147 |           text: "You should create the first development phase based on the implementation plan."
 5148 |         }]
 5149 |       };
 5150 |     }
 5151 |     
 5152 |     // Find the current active phase (the first non-completed phase)
 5153 |     const currentPhase = feature.phases.find(p => p.status !== 'completed' && p.status !== 'reviewed');
 5154 |     
 5155 |     if (!currentPhase) {
 5156 |       return {
 5157 |         content: [{
 5158 |           type: "text",
 5159 |           text: "All phases are complete. You should mark the final phase as reviewed."
 5160 |         }]
 5161 |       };
 5162 |     }
 5163 |     
 5164 |     // Check if all tasks in the phase are completed
 5165 |     const allTasksCompleted = currentPhase.tasks.every(t => t.completed);
 5166 |     
 5167 |     if (currentPhase.tasks.length === 0) {
 5168 |       return {
 5169 |         content: [{
 5170 |           type: "text",
 5171 |           text: `Current phase "${currentPhase.name}" has no tasks. You should add tasks based on the implementation plan.`
 5172 |         }]
 5173 |       };
 5174 |     } else if (!allTasksCompleted) {
 5175 |       const pendingTasks = currentPhase.tasks.filter(t => !t.completed);
 5176 |       
 5177 |       return {
 5178 |         content: [{
 5179 |           type: "text",
 5180 |           text: `Current phase "${currentPhase.name}" has ${pendingTasks.length} incomplete tasks. Complete these tasks before moving to the next phase.`
 5181 |         }]
 5182 |       };
 5183 |     } else {
 5184 |       return {
 5185 |         content: [{
 5186 |           type: "text",
 5187 |           text: `All tasks in the current phase "${currentPhase.name}" are complete. You can now mark this phase as completed and proceed to the next phase.`
 5188 |         }]
 5189 |       };
 5190 |     }
 5191 |   }
 5192 | );
 5193 | 
 5194 | // Define prompt for feature planning
 5195 | server.prompt(
 5196 |   "feature-planning",
 5197 |   { 
 5198 |     featureId: z.string() 
 5199 |   },
 5200 |   ({ featureId }) => ({
 5201 |     messages: [{
 5202 |       role: "user",
 5203 |       content: {
 5204 |         type: "text",
 5205 |         text: `I need to plan the development of feature with ID ${featureId}. Please help me:
 5206 | 1. Understand what the feature is about
 5207 | 2. Break down the feature into development phases 
 5208 | 3. Create tasks for each phase
 5209 | 4. Track progress through completion`
 5210 |       }
 5211 |     }]
 5212 |   })
 5213 | );
 5214 | 
 5215 | // Start the server
 5216 | async function main() {
 5217 |   console.error("Starting Vibe-Coder MCP Server...");
 5218 |   const transport = new StdioServerTransport();
 5219 |   await server.connect(transport);
 5220 | }
 5221 | 
 5222 | main().catch(error => {
 5223 |   console.error("Error in Vibe-Coder MCP Server:", error);
 5224 |   process.exit(1);
 5225 | });
 5226 | 
 5227 | ================
 5228 | File: src/phases.ts
 5229 | ================
 5230 | /**
 5231 |  * Phase management module for the Vibe-Coder MCP Server.
 5232 |  * This module handles the creation and management of development phases and tasks.
 5233 |  */
 5234 | import { Feature, Phase, Task, PhaseStatus } from './types.js';
 5235 | import { updateFeature, getFeature } from './storage.js';
 5236 | import { generateId, createPhaseObject, createTaskObject, isValidPhaseStatus, now } from './utils.js';
 5237 | 
 5238 | /**
 5239 |  * Define valid phase status transitions
 5240 |  * A map of current status to valid next statuses
 5241 |  */
 5242 | const VALID_PHASE_TRANSITIONS: Record<PhaseStatus, PhaseStatus[]> = {
 5243 |   'pending': ['in_progress'],
 5244 |   'in_progress': ['completed'],
 5245 |   'completed': ['reviewed'],
 5246 |   'reviewed': []
 5247 | };
 5248 | 
 5249 | /**
 5250 |  * Create a new phase for a feature
 5251 |  * @param featureId The ID of the feature to create the phase for
 5252 |  * @param name The name of the phase
 5253 |  * @param description The description of the phase
 5254 |  * @returns The created phase or undefined if the feature is not found
 5255 |  */
 5256 | export function createPhase(
 5257 |   featureId: string,
 5258 |   name: string,
 5259 |   description: string
 5260 | ): Phase | undefined {
 5261 |   const feature = getFeature(featureId);
 5262 |   if (!feature) return undefined;
 5263 |   
 5264 |   const newPhase = createPhaseObject(name, description);
 5265 |   
 5266 |   updateFeature(featureId, {
 5267 |     phases: [...feature.phases, newPhase]
 5268 |   });
 5269 |   
 5270 |   return newPhase;
 5271 | }
 5272 | 
 5273 | /**
 5274 |  * Get a phase by ID
 5275 |  * @param featureId The ID of the feature
 5276 |  * @param phaseId The ID of the phase to get
 5277 |  * @returns The phase or undefined if not found
 5278 |  */
 5279 | export function getPhase(
 5280 |   featureId: string,
 5281 |   phaseId: string
 5282 | ): Phase | undefined {
 5283 |   const feature = getFeature(featureId);
 5284 |   if (!feature) return undefined;
 5285 |   
 5286 |   return feature.phases.find(p => p.id === phaseId);
 5287 | }
 5288 | 
 5289 | /**
 5290 |  * Add a new phase to a feature
 5291 |  * @param featureId The ID of the feature to add the phase to
 5292 |  * @param name The name of the phase
 5293 |  * @param description The description of the phase
 5294 |  * @returns The updated feature or undefined if not found
 5295 |  */
 5296 | export function addPhase(
 5297 |   featureId: string,
 5298 |   name: string,
 5299 |   description: string
 5300 | ): Feature | undefined {
 5301 |   const feature = getFeature(featureId);
 5302 |   if (!feature) return undefined;
 5303 |   
 5304 |   const newPhase = createPhaseObject(name, description);
 5305 |   
 5306 |   return updateFeature(featureId, {
 5307 |     phases: [...feature.phases, newPhase]
 5308 |   });
 5309 | }
 5310 | 
 5311 | /**
 5312 |  * Add a task to a phase
 5313 |  * @param featureId The ID of the feature
 5314 |  * @param phaseId The ID of the phase to add the task to
 5315 |  * @param description The description of the task
 5316 |  * @returns The updated feature or undefined if not found
 5317 |  */
 5318 | export function addTask(
 5319 |   featureId: string,
 5320 |   phaseId: string,
 5321 |   description: string
 5322 | ): Feature | undefined {
 5323 |   const feature = getFeature(featureId);
 5324 |   if (!feature) return undefined;
 5325 |   
 5326 |   const phaseIndex = feature.phases.findIndex(p => p.id === phaseId);
 5327 |   if (phaseIndex === -1) return undefined;
 5328 |   
 5329 |   const newTask = createTaskObject(description);
 5330 |   
 5331 |   const updatedPhases = [...feature.phases];
 5332 |   updatedPhases[phaseIndex] = {
 5333 |     ...updatedPhases[phaseIndex],
 5334 |     tasks: [...updatedPhases[phaseIndex].tasks, newTask],
 5335 |     updatedAt: now()
 5336 |   };
 5337 |   
 5338 |   return updateFeature(featureId, { phases: updatedPhases });
 5339 | }
 5340 | 
 5341 | /**
 5342 |  * Update the status of a phase
 5343 |  * @param featureId The ID of the feature
 5344 |  * @param phaseId The ID of the phase to update
 5345 |  * @param status The new status
 5346 |  * @returns The updated feature or undefined if not found
 5347 |  */
 5348 | export function updatePhaseStatus(
 5349 |   featureId: string,
 5350 |   phaseId: string,
 5351 |   status: PhaseStatus
 5352 | ): Feature | undefined {
 5353 |   const feature = getFeature(featureId);
 5354 |   if (!feature) return undefined;
 5355 |   
 5356 |   const phaseIndex = feature.phases.findIndex(p => p.id === phaseId);
 5357 |   if (phaseIndex === -1) return undefined;
 5358 |   
 5359 |   // Validate the status transition
 5360 |   const phase = feature.phases[phaseIndex];
 5361 |   const validationResult = validatePhaseTransition(phase.status, status);
 5362 |   if (!validationResult.valid) {
 5363 |     console.error(validationResult.message);
 5364 |     return undefined;
 5365 |   }
 5366 |   
 5367 |   const updatedPhases = [...feature.phases];
 5368 |   updatedPhases[phaseIndex] = {
 5369 |     ...updatedPhases[phaseIndex],
 5370 |     status,
 5371 |     updatedAt: now()
 5372 |   };
 5373 |   
 5374 |   return updateFeature(featureId, { phases: updatedPhases });
 5375 | }
 5376 | 
 5377 | /**
 5378 |  * Update a task's completion status
 5379 |  * @param featureId The ID of the feature
 5380 |  * @param phaseId The ID of the phase
 5381 |  * @param taskId The ID of the task to update
 5382 |  * @param completed Whether the task is completed
 5383 |  * @returns The updated feature or undefined if not found
 5384 |  */
 5385 | export function updateTaskStatus(
 5386 |   featureId: string,
 5387 |   phaseId: string,
 5388 |   taskId: string,
 5389 |   completed: boolean
 5390 | ): Feature | undefined {
 5391 |   const feature = getFeature(featureId);
 5392 |   if (!feature) return undefined;
 5393 |   
 5394 |   const phaseIndex = feature.phases.findIndex(p => p.id === phaseId);
 5395 |   if (phaseIndex === -1) return undefined;
 5396 |   
 5397 |   const taskIndex = feature.phases[phaseIndex].tasks.findIndex(t => t.id === taskId);
 5398 |   if (taskIndex === -1) return undefined;
 5399 |   
 5400 |   const updatedPhases = [...feature.phases];
 5401 |   const updatedTasks = [...updatedPhases[phaseIndex].tasks];
 5402 |   
 5403 |   updatedTasks[taskIndex] = {
 5404 |     ...updatedTasks[taskIndex],
 5405 |     completed,
 5406 |     updatedAt: now()
 5407 |   };
 5408 |   
 5409 |   updatedPhases[phaseIndex] = {
 5410 |     ...updatedPhases[phaseIndex],
 5411 |     tasks: updatedTasks,
 5412 |     updatedAt: now()
 5413 |   };
 5414 |   
 5415 |   return updateFeature(featureId, { phases: updatedPhases });
 5416 | }
 5417 | 
 5418 | /**
 5419 |  * Validate a phase status transition
 5420 |  * @param currentStatus The current status
 5421 |  * @param newStatus The proposed new status
 5422 |  * @returns An object with valid flag and message
 5423 |  */
 5424 | export function validatePhaseTransition(
 5425 |   currentStatus: PhaseStatus,
 5426 |   newStatus: PhaseStatus
 5427 | ): { valid: boolean; message: string } {
 5428 |   // Allow same status
 5429 |   if (currentStatus === newStatus) {
 5430 |     return { valid: true, message: "Status unchanged" };
 5431 |   }
 5432 |   
 5433 |   // Check if the status is valid
 5434 |   if (!isValidPhaseStatus(newStatus)) {
 5435 |     return { 
 5436 |       valid: false, 
 5437 |       message: `Invalid status: ${newStatus}. Valid statuses are: pending, in_progress, completed, reviewed`
 5438 |     };
 5439 |   }
 5440 |   
 5441 |   // Check if the transition is valid
 5442 |   const validNextStatuses = VALID_PHASE_TRANSITIONS[currentStatus];
 5443 |   if (!validNextStatuses.includes(newStatus)) {
 5444 |     return {
 5445 |       valid: false,
 5446 |       message: `Invalid transition from ${currentStatus} to ${newStatus}. Valid next statuses are: ${validNextStatuses.join(', ')}`
 5447 |     };
 5448 |   }
 5449 |   
 5450 |   return { valid: true, message: "Valid transition" };
 5451 | }
 5452 | 
 5453 | /**
 5454 |  * Get the next logical status for a phase
 5455 |  * @param currentStatus The current status
 5456 |  * @returns The recommended next status, or null if no valid transition
 5457 |  */
 5458 | export function getNextPhaseStatus(currentStatus: PhaseStatus): PhaseStatus | null {
 5459 |   const validNextStatuses = VALID_PHASE_TRANSITIONS[currentStatus];
 5460 |   
 5461 |   if (validNextStatuses.length === 0) {
 5462 |     return null;
 5463 |   }
 5464 |   
 5465 |   return validNextStatuses[0];
 5466 | }
 5467 | 
 5468 | /**
 5469 |  * Get a summary of the phases for a feature
 5470 |  * @param featureId The ID of the feature
 5471 |  * @returns A text summary of the phases
 5472 |  */
 5473 | export function getPhaseSummary(featureId: string): string {
 5474 |   const feature = getFeature(featureId);
 5475 |   if (!feature) return "Feature not found";
 5476 |   
 5477 |   if (feature.phases.length === 0) {
 5478 |     return "No phases defined for this feature yet.";
 5479 |   }
 5480 |   
 5481 |   const phasesSummary = feature.phases.map(phase => {
 5482 |     const completedTasks = phase.tasks.filter(t => t.completed).length;
 5483 |     const totalTasks = phase.tasks.length;
 5484 |     return `${phase.name} (${phase.status}): ${completedTasks}/${totalTasks} tasks completed`;
 5485 |   }).join('\n');
 5486 |   
 5487 |   return `Phases for ${feature.name}:\n${phasesSummary}`;
 5488 | }
 5489 | 
 5490 | /**
 5491 |  * Initialize default phases for a feature based on its implementation plan
 5492 |  * @param featureId The ID of the feature
 5493 |  * @returns The updated feature or undefined if not found
 5494 |  */
 5495 | export function initializeDefaultPhases(featureId: string): Feature | undefined {
 5496 |   const feature = getFeature(featureId);
 5497 |   if (!feature) return undefined;
 5498 |   
 5499 |   // If the feature already has phases, don't override them
 5500 |   if (feature.phases && feature.phases.length > 0) {
 5501 |     return feature;
 5502 |   }
 5503 |   
 5504 |   // Create default phases
 5505 |   const defaultPhases = [
 5506 |     createPhaseObject(
 5507 |       "Requirements Analysis and Design",
 5508 |       "Analyze requirements, design the architecture, and create a detailed implementation plan."
 5509 |     ),
 5510 |     createPhaseObject(
 5511 |       "Core Implementation",
 5512 |       "Implement the core functionality based on the design."
 5513 |     ),
 5514 |     createPhaseObject(
 5515 |       "Testing and Integration",
 5516 |       "Test all components, integrate with existing systems, and refine the implementation."
 5517 |     ),
 5518 |     createPhaseObject(
 5519 |       "Documentation and Finalization",
 5520 |       "Finalize documentation, clean up code, and prepare for deployment."
 5521 |     )
 5522 |   ];
 5523 |   
 5524 |   // Add default tasks for each phase
 5525 |   const phase1 = defaultPhases[0];
 5526 |   addTask(featureId, phase1.id, "Review and analyze clarification responses");
 5527 |   addTask(featureId, phase1.id, "Identify key components and their interactions");
 5528 |   addTask(featureId, phase1.id, "Design the system architecture");
 5529 |   addTask(featureId, phase1.id, "Create UML diagrams if necessary");
 5530 |   addTask(featureId, phase1.id, "Identify potential edge cases and risks");
 5531 |   
 5532 |   const phase2 = defaultPhases[1];
 5533 |   addTask(featureId, phase2.id, "Set up project structure and dependencies");
 5534 |   addTask(featureId, phase2.id, "Implement data models and interfaces");
 5535 |   addTask(featureId, phase2.id, "Build core business logic");
 5536 |   addTask(featureId, phase2.id, "Create unit tests for core functionality");
 5537 |   addTask(featureId, phase2.id, "Ensure code follows best practices");
 5538 |   
 5539 |   const phase3 = defaultPhases[2];
 5540 |   addTask(featureId, phase3.id, "Write unit tests for all components");
 5541 |   addTask(featureId, phase3.id, "Perform integration testing");
 5542 |   addTask(featureId, phase3.id, "Fix bugs and edge cases");
 5543 |   addTask(featureId, phase3.id, "Optimize performance");
 5544 |   addTask(featureId, phase3.id, "Document any known limitations");
 5545 |   
 5546 |   const phase4 = defaultPhases[3];
 5547 |   addTask(featureId, phase4.id, "Complete inline code documentation");
 5548 |   addTask(featureId, phase4.id, "Create user documentation");
 5549 |   addTask(featureId, phase4.id, "Clean up and refactor code");
 5550 |   addTask(featureId, phase4.id, "Prepare deployment strategy");
 5551 |   addTask(featureId, phase4.id, "Create final pull request");
 5552 |   
 5553 |   return updateFeature(featureId, { phases: defaultPhases });
 5554 | }
 5555 | 
 5556 | ================
 5557 | File: src/registry.ts
 5558 | ================
 5559 | /**
 5560 |  * @file registry.ts
 5561 |  * @version 1.1.0
 5562 |  * 
 5563 |  * Provides registries for tools and resources in the Vibe-Coder MCP Server.
 5564 |  * These registries manage URI templates, matching, and tool handlers.
 5565 |  */
 5566 | 
 5567 | import { ResourceTemplate } from '@modelcontextprotocol/sdk/types.js';
 5568 | import { ErrorCode, createErrorResponse, createToolErrorResponse } from './errors.js';
 5569 | import { Feature } from './types.js';
 5570 | 
 5571 | // --------- Tool Registry ---------
 5572 | 
 5573 | /**
 5574 |  * Type for tool handler function
 5575 |  */
 5576 | export type ToolHandler<T = any> = (params: T) => Promise<any>;
 5577 | 
 5578 | /**
 5579 |  * Tool metadata type
 5580 |  */
 5581 | export interface ToolMetadata {
 5582 |   description: string;
 5583 |   inputSchema: any;
 5584 |   examples?: any[];
 5585 | }
 5586 | 
 5587 | /**
 5588 |  * Tool registry to map tool names to their handler functions and metadata
 5589 |  */
 5590 | export class ToolRegistry {
 5591 |   private handlers: Map<string, ToolHandler> = new Map();
 5592 |   private toolMetadata: Map<string, ToolMetadata> = new Map();
 5593 |   
 5594 |   /**
 5595 |    * Register a tool handler with metadata
 5596 |    * @param name Tool name
 5597 |    * @param handler Tool handler function
 5598 |    * @param description Tool description
 5599 |    * @param inputSchema Tool input schema
 5600 |    * @param examples Optional examples for the tool
 5601 |    */
 5602 |   register<T>(
 5603 |     name: string, 
 5604 |     handler: ToolHandler<T>, 
 5605 |     description: string, 
 5606 |     inputSchema: any,
 5607 |     examples?: any[]
 5608 |   ): void {
 5609 |     this.handlers.set(name, handler);
 5610 |     this.toolMetadata.set(name, { 
 5611 |       description, 
 5612 |       inputSchema,
 5613 |       examples 
 5614 |     });
 5615 |   }
 5616 |   
 5617 |   /**
 5618 |    * Get a tool handler by name
 5619 |    * @param name Tool name
 5620 |    * @returns The tool handler function or undefined if not found
 5621 |    */
 5622 |   getHandler(name: string): ToolHandler | undefined {
 5623 |     return this.handlers.get(name);
 5624 |   }
 5625 |   
 5626 |   /**
 5627 |    * Get tool metadata by name
 5628 |    * @param name Tool name
 5629 |    * @returns The tool metadata or undefined if not found
 5630 |    */
 5631 |   getMetadata(name: string): ToolMetadata | undefined {
 5632 |     return this.toolMetadata.get(name);
 5633 |   }
 5634 |   
 5635 |   /**
 5636 |    * Check if a tool exists
 5637 |    * @param name Tool name
 5638 |    * @returns True if the tool exists
 5639 |    */
 5640 |   hasHandler(name: string): boolean {
 5641 |     return this.handlers.has(name);
 5642 |   }
 5643 |   
 5644 |   /**
 5645 |    * Execute a tool by name with parameters
 5646 |    * @param name Tool name
 5647 |    * @param params Tool parameters
 5648 |    * @returns The tool execution result
 5649 |    */
 5650 |   async execute(name: string, params: any): Promise<any> {
 5651 |     const handler = this.getHandler(name);
 5652 |     
 5653 |     if (!handler) {
 5654 |       return createToolErrorResponse(`Unknown tool "${name}"`);
 5655 |     }
 5656 |     
 5657 |     try {
 5658 |       return await handler(params);
 5659 |     } catch (error) {
 5660 |       console.error(`Error executing tool ${name}:`, error);
 5661 |       return createToolErrorResponse(
 5662 |         error instanceof Error ? error.message : "Internal server error"
 5663 |       );
 5664 |     }
 5665 |   }
 5666 |   
 5667 |   /**
 5668 |    * List all registered tools with their metadata
 5669 |    * @returns Array of tool information objects
 5670 |    */
 5671 |   listTools(): { name: string; description: string; inputSchema: any; examples?: any[] }[] {
 5672 |     return Array.from(this.handlers.keys()).map((name) => {
 5673 |       const metadata = this.toolMetadata.get(name);
 5674 |       return {
 5675 |         name,
 5676 |         description: metadata?.description || "No description provided",
 5677 |         inputSchema: metadata?.inputSchema || {},
 5678 |         examples: metadata?.examples
 5679 |       };
 5680 |     });
 5681 |   }
 5682 | }
 5683 | 
 5684 | // --------- Resource Registry ---------
 5685 | 
 5686 | /**
 5687 |  * Resource handler type
 5688 |  */
 5689 | export type ResourceHandler = (uri: URL, params: Record<string, string>) => Promise<any>;
 5690 | 
 5691 | /**
 5692 |  * Resource registry entry
 5693 |  */
 5694 | type ResourceRegistryEntry = {
 5695 |   template: ResourceTemplate;
 5696 |   handler: ResourceHandler;
 5697 | };
 5698 | 
 5699 | /**
 5700 |  * Resource registry for managing URI templates and handlers
 5701 |  */
 5702 | export class ResourceRegistry {
 5703 |   private resources: ResourceRegistryEntry[] = [];
 5704 |   
 5705 |   /**
 5706 |    * Register a resource with a template and handler
 5707 |    */
 5708 |   register(template: ResourceTemplate, handler: ResourceHandler): void {
 5709 |     this.resources.push({ template, handler });
 5710 |   }
 5711 |   
 5712 |   /**
 5713 |    * Find a matching resource and extract parameters
 5714 |    */
 5715 |   findMatch(uri: string): { handler: ResourceHandler; params: Record<string, string> } | undefined {
 5716 |     const url = new URL(uri);
 5717 |     
 5718 |     for (const { template, handler } of this.resources) {
 5719 |       const match = this.matchTemplate(url, template);
 5720 |       
 5721 |       if (match) {
 5722 |         return { handler, params: match };
 5723 |       }
 5724 |     }
 5725 |     
 5726 |     return undefined;
 5727 |   }
 5728 |   
 5729 |   /**
 5730 |    * Match a URL against a template and extract parameters
 5731 |    */
 5732 |   private matchTemplate(url: URL, template: ResourceTemplate): Record<string, string> | undefined {
 5733 |     // Convert template to regex pattern
 5734 |     const pattern = this.templateToPattern(template.pattern);
 5735 |     const regex = new RegExp(pattern.pattern);
 5736 |     
 5737 |     // Match against the full URL
 5738 |     const match = regex.exec(url.href);
 5739 |     
 5740 |     if (!match) {
 5741 |       return undefined;
 5742 |     }
 5743 |     
 5744 |     // Extract named parameters
 5745 |     const params: Record<string, string> = {};
 5746 |     
 5747 |     pattern.paramNames.forEach((name, index) => {
 5748 |       params[name] = match[index + 1] || '';
 5749 |     });
 5750 |     
 5751 |     return params;
 5752 |   }
 5753 |   
 5754 |   /**
 5755 |    * Convert a URI template to a regex pattern
 5756 |    * Handles {param} syntax in templates
 5757 |    */
 5758 |   private templateToPattern(template: string): { pattern: string; paramNames: string[] } {
 5759 |     const paramNames: string[] = [];
 5760 |     let pattern = template.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
 5761 |     
 5762 |     // Replace {param} with capture groups
 5763 |     pattern = pattern.replace(/\{([a-zA-Z0-9_]+)\}/g, (_, name) => {
 5764 |       paramNames.push(name);
 5765 |       return '([^/]+)';
 5766 |     });
 5767 |     
 5768 |     // Replace * with wildcard
 5769 |     pattern = pattern.replace(/\\\*/g, '.*');
 5770 |     
 5771 |     // Anchor to start of string
 5772 |     pattern = `^${pattern}$`;
 5773 |     
 5774 |     return { pattern, paramNames };
 5775 |   }
 5776 |   
 5777 |   /**
 5778 |    * List all registered resources
 5779 |    * @returns Array of resource templates
 5780 |    */
 5781 |   listResources(): { template: string }[] {
 5782 |     return this.resources.map(({ template }) => ({
 5783 |       template: template.pattern
 5784 |     }));
 5785 |   }
 5786 | }
 5787 | 
 5788 | // Create global instances
 5789 | export const toolRegistry = new ToolRegistry();
 5790 | export const resourceRegistry = new ResourceRegistry();
 5791 | 
 5792 | ================
 5793 | File: src/resource-handlers.ts
 5794 | ================
 5795 | /**
 5796 |  * @file resource-handlers.ts
 5797 |  * @version 1.0.0
 5798 |  * 
 5799 |  * Provides handlers for resources exposed by the Vibe-Coder MCP Server.
 5800 |  * These handlers are registered with the resource registry for consistent handling.
 5801 |  */
 5802 | 
 5803 | import { ResourceTemplate } from '@modelcontextprotocol/sdk/types.js';
 5804 | import { resourceRegistry, ResourceHandler } from './registry.js';
 5805 | import { Feature } from './types.js';
 5806 | import { listFeatures, getFeature } from './storage.js';
 5807 | import { formatClarificationResponses } from './clarification.js';
 5808 | import { generatePRD, generateImplementationPlan } from './documentation.js';
 5809 | import { generateFeatureProgressSummary } from './utils.js';
 5810 | import { ErrorCode, createErrorResponse } from './errors.js';
 5811 | 
 5812 | /**
 5813 |  * Define resource templates for all resources
 5814 |  */
 5815 | const RESOURCE_TEMPLATES = {
 5816 |   featuresList: new ResourceTemplate('features://list', { list: undefined }),
 5817 |   featuresStatus: new ResourceTemplate('features://status', { list: undefined }),
 5818 |   featureDetail: new ResourceTemplate('feature://{featureId}', { list: undefined }),
 5819 |   featureProgress: new ResourceTemplate('feature://{featureId}/progress', { list: undefined }),
 5820 |   featurePrd: new ResourceTemplate('feature://{featureId}/prd', { list: undefined }),
 5821 |   featureImplementation: new ResourceTemplate('feature://{featureId}/implementation', { list: undefined }),
 5822 |   featurePhases: new ResourceTemplate('feature://{featureId}/phases', { list: undefined }),
 5823 |   featureTasks: new ResourceTemplate('feature://{featureId}/tasks', { list: undefined }),
 5824 |   phaseDetail: new ResourceTemplate('feature://{featureId}/phase/{phaseId}', { list: undefined }),
 5825 |   phaseTasks: new ResourceTemplate('feature://{featureId}/phase/{phaseId}/tasks', { list: undefined }),
 5826 |   taskDetail: new ResourceTemplate('feature://{featureId}/phase/{phaseId}/task/{taskId}', { list: undefined }),
 5827 | };
 5828 | 
 5829 | /**
 5830 |  * Handler for the features list resource
 5831 |  */
 5832 | const featuresListHandler: ResourceHandler = async (uri, params) => {
 5833 |   return {
 5834 |     contents: [{
 5835 |       uri: uri.href,
 5836 |       mimeType: "text/plain",
 5837 |       text: listFeatures().map(f => `${f.id}: ${f.name}`).join("\n")
 5838 |     }]
 5839 |   };
 5840 | };
 5841 | 
 5842 | /**
 5843 |  * Handler for the features status resource
 5844 |  */
 5845 | const featuresStatusHandler: ResourceHandler = async (uri, params) => {
 5846 |   const features = listFeatures();
 5847 |   
 5848 |   if (features.length === 0) {
 5849 |     return {
 5850 |       contents: [{
 5851 |         uri: uri.href,
 5852 |         mimeType: "text/markdown",
 5853 |         text: "# Project Status\n\nNo features have been created yet."
 5854 |       }]
 5855 |     };
 5856 |   }
 5857 |   
 5858 |   const featuresStatus = features.map(feature => {
 5859 |     const totalPhases = feature.phases.length;
 5860 |     const completedPhases = feature.phases.filter(p => p.status === 'completed' || p.status === 'reviewed').length;
 5861 |     const totalTasks = feature.phases.reduce((acc, phase) => acc + phase.tasks.length, 0);
 5862 |     const completedTasks = feature.phases.reduce(
 5863 |       (acc, phase) => acc + phase.tasks.filter(t => t.completed).length, 0
 5864 |     );
 5865 |     
 5866 |     return `## ${feature.name}
 5867 | - ID: ${feature.id}
 5868 | - Status: ${completedPhases === totalPhases && totalPhases > 0 ? 'Completed' : 'In Progress'}
 5869 | - Phases: ${completedPhases}/${totalPhases} completed
 5870 | - Tasks: ${completedTasks}/${totalTasks} completed
 5871 | - [View Details](feature://${feature.id}/progress)
 5872 | `;
 5873 |   }).join('\n');
 5874 |   
 5875 |   return {
 5876 |     contents: [{
 5877 |       uri: uri.href,
 5878 |       mimeType: "text/markdown",
 5879 |       text: `# Project Status\n\n${featuresStatus}`
 5880 |     }]
 5881 |   };
 5882 | };
 5883 | 
 5884 | /**
 5885 |  * Handler for the feature detail resource
 5886 |  */
 5887 | const featureDetailHandler: ResourceHandler = async (uri, params) => {
 5888 |   const featureId = params.featureId;
 5889 |   const feature = getFeature(featureId);
 5890 |   
 5891 |   if (!feature) {
 5892 |     return createErrorResponse(ErrorCode.FEATURE_NOT_FOUND, `Feature ${featureId} not found`);
 5893 |   }
 5894 |   
 5895 |   const timestamp = feature.updatedAt.toISOString();
 5896 |   const clarifications = formatClarificationResponses(feature.clarificationResponses);
 5897 |   const phasesText = feature.phases.map(p => 
 5898 |     `- ${p.name} (${p.status}): ${p.tasks.filter(t => t.completed).length}/${p.tasks.length} tasks completed`
 5899 |   ).join('\n');
 5900 |   
 5901 |   const featureDetails = `
 5902 | Feature: ${feature.name}
 5903 | ID: ${feature.id}
 5904 | Description: ${feature.description}
 5905 | Last Updated: ${timestamp}
 5906 | 
 5907 | Clarification Responses:
 5908 | ${clarifications}
 5909 | 
 5910 | Phases (${feature.phases.length}):
 5911 | ${phasesText}
 5912 | `;
 5913 |   
 5914 |   return {
 5915 |     contents: [{
 5916 |       uri: uri.href,
 5917 |       mimeType: "text/plain",
 5918 |       text: featureDetails
 5919 |     }]
 5920 |   };
 5921 | };
 5922 | 
 5923 | /**
 5924 |  * Handler for the feature progress resource
 5925 |  */
 5926 | const featureProgressHandler: ResourceHandler = async (uri, params) => {
 5927 |   const featureId = params.featureId;
 5928 |   const feature = getFeature(featureId);
 5929 |   
 5930 |   if (!feature) {
 5931 |     return createErrorResponse(ErrorCode.FEATURE_NOT_FOUND, `Feature ${featureId} not found`);
 5932 |   }
 5933 |   
 5934 |   const progressReport = generateFeatureProgressSummary(feature);
 5935 |   
 5936 |   return {
 5937 |     contents: [{
 5938 |       uri: uri.href,
 5939 |       mimeType: "text/markdown",
 5940 |       text: progressReport
 5941 |     }]
 5942 |   };
 5943 | };
 5944 | 
 5945 | /**
 5946 |  * Handler for the feature PRD resource
 5947 |  */
 5948 | const featurePrdHandler: ResourceHandler = async (uri, params) => {
 5949 |   const featureId = params.featureId;
 5950 |   const feature = getFeature(featureId);
 5951 |   
 5952 |   if (!feature) {
 5953 |     return createErrorResponse(ErrorCode.FEATURE_NOT_FOUND, `Feature ${featureId} not found`);
 5954 |   }
 5955 |   
 5956 |   const prdContent = feature.prdDoc || generatePRD(feature);
 5957 |   
 5958 |   return {
 5959 |     contents: [{
 5960 |       uri: uri.href,
 5961 |       mimeType: "text/markdown",
 5962 |       text: prdContent
 5963 |     }]
 5964 |   };
 5965 | };
 5966 | 
 5967 | /**
 5968 |  * Handler for the feature implementation plan resource
 5969 |  */
 5970 | const featureImplementationHandler: ResourceHandler = async (uri, params) => {
 5971 |   const featureId = params.featureId;
 5972 |   const feature = getFeature(featureId);
 5973 |   
 5974 |   if (!feature) {
 5975 |     return createErrorResponse(ErrorCode.FEATURE_NOT_FOUND, `Feature ${featureId} not found`);
 5976 |   }
 5977 |   
 5978 |   const implContent = feature.implDoc || generateImplementationPlan(feature);
 5979 |   
 5980 |   return {
 5981 |     contents: [{
 5982 |       uri: uri.href,
 5983 |       mimeType: "text/markdown",
 5984 |       text: implContent
 5985 |     }]
 5986 |   };
 5987 | };
 5988 | 
 5989 | /**
 5990 |  * Handler for the feature phases resource
 5991 |  */
 5992 | const featurePhasesHandler: ResourceHandler = async (uri, params) => {
 5993 |   const featureId = params.featureId;
 5994 |   const feature = getFeature(featureId);
 5995 |   
 5996 |   if (!feature) {
 5997 |     return createErrorResponse(ErrorCode.FEATURE_NOT_FOUND, `Feature ${featureId} not found`);
 5998 |   }
 5999 |   
 6000 |   if (feature.phases.length === 0) {
 6001 |     return {
 6002 |       contents: [{
 6003 |         uri: uri.href,
 6004 |         mimeType: "text/plain",
 6005 |         text: `No phases defined for feature: ${feature.name}`
 6006 |       }]
 6007 |     };
 6008 |   }
 6009 |   
 6010 |   const phasesContent = feature.phases.map(phase => {
 6011 |     const completedTasks = phase.tasks.filter(t => t.completed).length;
 6012 |     const totalTasks = phase.tasks.length;
 6013 |     return `Phase: ${phase.name} (ID: ${phase.id})
 6014 | Status: ${phase.status}
 6015 | Description: ${phase.description}
 6016 | Progress: ${completedTasks}/${totalTasks} tasks completed
 6017 | Last Updated: ${phase.updatedAt.toISOString()}
 6018 | `;
 6019 |   }).join('\n---\n\n');
 6020 |   
 6021 |   return {
 6022 |     contents: [{
 6023 |       uri: uri.href,
 6024 |       mimeType: "text/plain",
 6025 |       text: `# Phases for Feature: ${feature.name}\n\n${phasesContent}`
 6026 |     }]
 6027 |   };
 6028 | };
 6029 | 
 6030 | /**
 6031 |  * Handler for the feature tasks resource
 6032 |  */
 6033 | const featureTasksHandler: ResourceHandler = async (uri, params) => {
 6034 |   const featureId = params.featureId;
 6035 |   const feature = getFeature(featureId);
 6036 |   
 6037 |   if (!feature) {
 6038 |     return createErrorResponse(ErrorCode.FEATURE_NOT_FOUND, `Feature ${featureId} not found`);
 6039 |   }
 6040 |   
 6041 |   const allTasks = feature.phases.flatMap(phase => 
 6042 |     phase.tasks.map(task => ({
 6043 |       ...task,
 6044 |       phaseName: phase.name,
 6045 |       phaseId: phase.id,
 6046 |       phaseStatus: phase.status
 6047 |     }))
 6048 |   );
 6049 |   
 6050 |   if (allTasks.length === 0) {
 6051 |     return {
 6052 |       contents: [{
 6053 |         uri: uri.href,
 6054 |         mimeType: "text/plain",
 6055 |         text: `No tasks defined for feature: ${feature.name}`
 6056 |       }]
 6057 |     };
 6058 |   }
 6059 |   
 6060 |   const pendingTasks = allTasks.filter(t => !t.completed);
 6061 |   const completedTasks = allTasks.filter(t => t.completed);
 6062 |   
 6063 |   const pendingTasksText = pendingTasks.length > 0 
 6064 |     ? pendingTasks.map(task => `- [ ] ${task.description} (ID: ${task.id}, Phase: ${task.phaseName})`).join('\n')
 6065 |     : "No pending tasks.";
 6066 |     
 6067 |   const completedTasksText = completedTasks.length > 0
 6068 |     ? completedTasks.map(task => `- [x] ${task.description} (ID: ${task.id}, Phase: ${task.phaseName})`).join('\n')
 6069 |     : "No completed tasks.";
 6070 |   
 6071 |   const tasksContent = `# All Tasks for Feature: ${feature.name}
 6072 | 
 6073 | ## Pending Tasks (${pendingTasks.length})
 6074 | ${pendingTasksText}
 6075 | 
 6076 | ## Completed Tasks (${completedTasks.length})
 6077 | ${completedTasksText}
 6078 | `;
 6079 |   
 6080 |   return {
 6081 |     contents: [{
 6082 |       uri: uri.href,
 6083 |       mimeType: "text/plain",
 6084 |       text: tasksContent
 6085 |     }]
 6086 |   };
 6087 | };
 6088 | 
 6089 | /**
 6090 |  * Handler for the phase detail resource
 6091 |  */
 6092 | const phaseDetailHandler: ResourceHandler = async (uri, params) => {
 6093 |   const featureId = params.featureId;
 6094 |   const phaseId = params.phaseId;
 6095 |   
 6096 |   const feature = getFeature(featureId);
 6097 |   
 6098 |   if (!feature) {
 6099 |     return createErrorResponse(ErrorCode.FEATURE_NOT_FOUND, `Feature ${featureId} not found`);
 6100 |   }
 6101 |   
 6102 |   const phase = feature.phases.find(p => p.id === phaseId);
 6103 |   
 6104 |   if (!phase) {
 6105 |     return createErrorResponse(ErrorCode.PHASE_NOT_FOUND, `Phase ${phaseId} not found in feature ${feature.name}`);
 6106 |   }
 6107 |   
 6108 |   const completedTasks = phase.tasks.filter(t => t.completed).length;
 6109 |   const totalTasks = phase.tasks.length;
 6110 |   
 6111 |   const taskList = phase.tasks.map(task => 
 6112 |     `- [${task.completed ? 'x' : ' '}] ${task.description} (ID: ${task.id})`
 6113 |   ).join('\n');
 6114 |   
 6115 |   const phaseDetails = `
 6116 | Phase: ${phase.name}
 6117 | ID: ${phase.id}
 6118 | Status: ${phase.status}
 6119 | Description: ${phase.description}
 6120 | Created: ${phase.createdAt.toISOString()}
 6121 | Last Updated: ${phase.updatedAt.toISOString()}
 6122 | Progress: ${completedTasks}/${totalTasks} tasks completed
 6123 | 
 6124 | Tasks:
 6125 | ${taskList}
 6126 | `;
 6127 |   
 6128 |   return {
 6129 |     contents: [{
 6130 |       uri: uri.href,
 6131 |       mimeType: "text/plain",
 6132 |       text: phaseDetails
 6133 |     }]
 6134 |   };
 6135 | };
 6136 | 
 6137 | /**
 6138 |  * Handler for the phase tasks resource
 6139 |  */
 6140 | const phaseTasksHandler: ResourceHandler = async (uri, params) => {
 6141 |   const featureId = params.featureId;
 6142 |   const phaseId = params.phaseId;
 6143 |   
 6144 |   const feature = getFeature(featureId);
 6145 |   
 6146 |   if (!feature) {
 6147 |     return createErrorResponse(ErrorCode.FEATURE_NOT_FOUND, `Feature ${featureId} not found`);
 6148 |   }
 6149 |   
 6150 |   const phase = feature.phases.find(p => p.id === phaseId);
 6151 |   
 6152 |   if (!phase) {
 6153 |     return createErrorResponse(ErrorCode.PHASE_NOT_FOUND, `Phase ${phaseId} not found in feature ${feature.name}`);
 6154 |   }
 6155 |   
 6156 |   if (phase.tasks.length === 0) {
 6157 |     return {
 6158 |       contents: [{
 6159 |         uri: uri.href,
 6160 |         mimeType: "text/plain",
 6161 |         text: `No tasks defined for phase: ${phase.name}`
 6162 |       }]
 6163 |     };
 6164 |   }
 6165 |   
 6166 |   const tasksContent = phase.tasks.map(task => `
 6167 | Task: ${task.description}
 6168 | ID: ${task.id}
 6169 | Status: ${task.completed ? 'Completed' : 'Pending'}
 6170 | Created: ${task.createdAt.toISOString()}
 6171 | Last Updated: ${task.updatedAt.toISOString()}
 6172 | `).join('\n---\n');
 6173 |   
 6174 |   return {
 6175 |     contents: [{
 6176 |       uri: uri.href,
 6177 |       mimeType: "text/plain",
 6178 |       text: `# Tasks for Phase: ${phase.name}\n\n${tasksContent}`
 6179 |     }]
 6180 |   };
 6181 | };
 6182 | 
 6183 | /**
 6184 |  * Handler for the task detail resource
 6185 |  */
 6186 | const taskDetailHandler: ResourceHandler = async (uri, params) => {
 6187 |   const featureId = params.featureId;
 6188 |   const phaseId = params.phaseId;
 6189 |   const taskId = params.taskId;
 6190 |   
 6191 |   const feature = getFeature(featureId);
 6192 |   
 6193 |   if (!feature) {
 6194 |     return createErrorResponse(ErrorCode.FEATURE_NOT_FOUND, `Feature ${featureId} not found`);
 6195 |   }
 6196 |   
 6197 |   const phase = feature.phases.find(p => p.id === phaseId);
 6198 |   
 6199 |   if (!phase) {
 6200 |     return createErrorResponse(ErrorCode.PHASE_NOT_FOUND, `Phase ${phaseId} not found in feature ${feature.name}`);
 6201 |   }
 6202 |   
 6203 |   const task = phase.tasks.find(t => t.id === taskId);
 6204 |   
 6205 |   if (!task) {
 6206 |     return createErrorResponse(ErrorCode.TASK_NOT_FOUND, `Task ${taskId} not found in phase ${phase.name}`);
 6207 |   }
 6208 |   
 6209 |   const taskDetails = `
 6210 | Task: ${task.description}
 6211 | ID: ${task.id}
 6212 | Status: ${task.completed ? 'Completed' : 'Pending'}
 6213 | Created: ${task.createdAt.toISOString()}
 6214 | Last Updated: ${task.updatedAt.toISOString()}
 6215 | `;
 6216 |   
 6217 |   return {
 6218 |     contents: [{
 6219 |       uri: uri.href,
 6220 |       mimeType: "text/plain",
 6221 |       text: taskDetails
 6222 |     }]
 6223 |   };
 6224 | };
 6225 | 
 6226 | /**
 6227 |  * Register all resource handlers
 6228 |  */
 6229 | export function registerResourceHandlers() {
 6230 |   resourceRegistry.register(RESOURCE_TEMPLATES.featuresList, featuresListHandler);
 6231 |   resourceRegistry.register(RESOURCE_TEMPLATES.featuresStatus, featuresStatusHandler);
 6232 |   resourceRegistry.register(RESOURCE_TEMPLATES.featureDetail, featureDetailHandler);
 6233 |   resourceRegistry.register(RESOURCE_TEMPLATES.featureProgress, featureProgressHandler);
 6234 |   resourceRegistry.register(RESOURCE_TEMPLATES.featurePrd, featurePrdHandler);
 6235 |   resourceRegistry.register(RESOURCE_TEMPLATES.featureImplementation, featureImplementationHandler);
 6236 |   resourceRegistry.register(RESOURCE_TEMPLATES.featurePhases, featurePhasesHandler);
 6237 |   resourceRegistry.register(RESOURCE_TEMPLATES.featureTasks, featureTasksHandler);
 6238 |   resourceRegistry.register(RESOURCE_TEMPLATES.phaseDetail, phaseDetailHandler);
 6239 |   resourceRegistry.register(RESOURCE_TEMPLATES.phaseTasks, phaseTasksHandler);
 6240 |   resourceRegistry.register(RESOURCE_TEMPLATES.taskDetail, taskDetailHandler);
 6241 | }
 6242 | 
 6243 | // Export individual handlers for testing or direct usage
 6244 | export {
 6245 |   featuresListHandler,
 6246 |   featuresStatusHandler,
 6247 |   featureDetailHandler,
 6248 |   featureProgressHandler,
 6249 |   featurePrdHandler,
 6250 |   featureImplementationHandler,
 6251 |   featurePhasesHandler,
 6252 |   featureTasksHandler,
 6253 |   phaseDetailHandler,
 6254 |   phaseTasksHandler,
 6255 |   taskDetailHandler
 6256 | };
 6257 | 
 6258 | ================
 6259 | File: src/schemas.ts
 6260 | ================
 6261 | /**
 6262 |  * @file schemas.ts
 6263 |  * @version 1.0.0
 6264 |  * 
 6265 |  * Provides Zod schemas and branded types for the Vibe-Coder MCP Server.
 6266 |  * These schemas enable runtime validation and improve type safety across the codebase.
 6267 |  */
 6268 | 
 6269 | import { z } from 'zod';
 6270 | import { PhaseStatus } from './types.js';
 6271 | 
 6272 | // --------- Branded Types for IDs ---------
 6273 | 
 6274 | /**
 6275 |  * Branded type for Feature IDs
 6276 |  */
 6277 | export type FeatureId = string & { readonly _brand: unique symbol };
 6278 | 
 6279 | /**
 6280 |  * Branded type for Phase IDs
 6281 |  */
 6282 | export type PhaseId = string & { readonly _brand: unique symbol };
 6283 | 
 6284 | /**
 6285 |  * Branded type for Task IDs
 6286 |  */
 6287 | export type TaskId = string & { readonly _brand: unique symbol };
 6288 | 
 6289 | /**
 6290 |  * Type guards for branded types
 6291 |  */
 6292 | export const isFeatureId = (id: string): id is FeatureId => id.startsWith('feature-');
 6293 | export const isPhaseId = (id: string): id is PhaseId => id.startsWith('phase-');
 6294 | export const isTaskId = (id: string): id is TaskId => id.startsWith('task-');
 6295 | 
 6296 | /**
 6297 |  * Brand creator functions
 6298 |  */
 6299 | export const createFeatureId = (id: string): FeatureId => {
 6300 |   if (!isFeatureId(id)) throw new Error(`Invalid feature ID format: ${id}`);
 6301 |   return id as FeatureId;
 6302 | };
 6303 | 
 6304 | export const createPhaseId = (id: string): PhaseId => {
 6305 |   if (!isPhaseId(id)) throw new Error(`Invalid phase ID format: ${id}`);
 6306 |   return id as PhaseId;
 6307 | };
 6308 | 
 6309 | export const createTaskId = (id: string): TaskId => {
 6310 |   if (!isTaskId(id)) throw new Error(`Invalid task ID format: ${id}`);
 6311 |   return id as TaskId;
 6312 | };
 6313 | 
 6314 | // --------- Core Zod Schemas ---------
 6315 | 
 6316 | /**
 6317 |  * Schema for ClarificationResponse
 6318 |  */
 6319 | export const ClarificationResponseSchema = z.object({
 6320 |   question: z.string().min(1, "Question cannot be empty"),
 6321 |   answer: z.string().min(1, "Answer cannot be empty"),
 6322 |   timestamp: z.date(),
 6323 | });
 6324 | 
 6325 | /**
 6326 |  * Schema for Task
 6327 |  */
 6328 | export const TaskSchema = z.object({
 6329 |   id: z.string().refine(isTaskId, "Invalid task ID format"),
 6330 |   description: z.string().min(3, "Task description must be at least 3 characters"),
 6331 |   completed: z.boolean(),
 6332 |   createdAt: z.date(),
 6333 |   updatedAt: z.date(),
 6334 | });
 6335 | 
 6336 | /**
 6337 |  * Schema for PhaseStatus
 6338 |  */
 6339 | export const PhaseStatusSchema = z.enum(["pending", "in_progress", "completed", "reviewed"]);
 6340 | 
 6341 | /**
 6342 |  * Schema for Phase
 6343 |  */
 6344 | export const PhaseSchema = z.object({
 6345 |   id: z.string().refine(isPhaseId, "Invalid phase ID format"),
 6346 |   name: z.string().min(2, "Phase name must be at least 2 characters").max(100, "Phase name must be at most 100 characters"),
 6347 |   description: z.string(),
 6348 |   tasks: z.array(TaskSchema),
 6349 |   status: PhaseStatusSchema,
 6350 |   createdAt: z.date(),
 6351 |   updatedAt: z.date(),
 6352 | });
 6353 | 
 6354 | /**
 6355 |  * Schema for Feature
 6356 |  */
 6357 | export const FeatureSchema = z.object({
 6358 |   id: z.string().refine(isFeatureId, "Invalid feature ID format"),
 6359 |   name: z.string().min(2, "Feature name must be at least 2 characters").max(100, "Feature name must be at most 100 characters"),
 6360 |   description: z.string(),
 6361 |   clarificationResponses: z.array(ClarificationResponseSchema),
 6362 |   prd: z.string().optional(),
 6363 |   prdDoc: z.string().optional(),
 6364 |   implementationPlan: z.string().optional(),
 6365 |   implDoc: z.string().optional(),
 6366 |   phases: z.array(PhaseSchema),
 6367 |   createdAt: z.date(),
 6368 |   updatedAt: z.date(),
 6369 | });
 6370 | 
 6371 | // --------- Type Inference ---------
 6372 | 
 6373 | /**
 6374 |  * Zod-inferred types to ensure schema and type compatibility
 6375 |  */
 6376 | export type ZodFeature = z.infer<typeof FeatureSchema>;
 6377 | export type ZodPhase = z.infer<typeof PhaseSchema>;
 6378 | export type ZodTask = z.infer<typeof TaskSchema>;
 6379 | export type ZodClarificationResponse = z.infer<typeof ClarificationResponseSchema>;
 6380 | 
 6381 | /**
 6382 |  * Validation functions for inputs
 6383 |  */
 6384 | export const validateFeature = (feature: unknown): ZodFeature => {
 6385 |   return FeatureSchema.parse(feature);
 6386 | };
 6387 | 
 6388 | export const validatePhase = (phase: unknown): ZodPhase => {
 6389 |   return PhaseSchema.parse(phase);
 6390 | };
 6391 | 
 6392 | export const validateTask = (task: unknown): ZodTask => {
 6393 |   return TaskSchema.parse(task);
 6394 | };
 6395 | 
 6396 | export const validateClarificationResponse = (response: unknown): ZodClarificationResponse => {
 6397 |   return ClarificationResponseSchema.parse(response);
 6398 | };
 6399 | 
 6400 | ================
 6401 | File: src/storage.ts
 6402 | ================
 6403 | /**
 6404 |  * In-memory storage for features and related data.
 6405 |  */
 6406 | import { Feature, FeatureStorage } from './types.js';
 6407 | 
 6408 | /**
 6409 |  * In-memory storage for features
 6410 |  */
 6411 | export const features: FeatureStorage = {};
 6412 | 
 6413 | /**
 6414 |  * Add a new feature to storage
 6415 |  * @param feature The feature to store
 6416 |  * @returns The stored feature
 6417 |  */
 6418 | export function storeFeature(feature: Feature): Feature {
 6419 |   features[feature.id] = feature;
 6420 |   return feature;
 6421 | }
 6422 | 
 6423 | /**
 6424 |  * Retrieve a feature by ID
 6425 |  * @param id The feature ID
 6426 |  * @returns The feature or undefined if not found
 6427 |  */
 6428 | export function getFeature(id: string): Feature | undefined {
 6429 |   return features[id];
 6430 | }
 6431 | 
 6432 | /**
 6433 |  * Update an existing feature
 6434 |  * @param id The feature ID
 6435 |  * @param updatedFields Fields to update on the feature
 6436 |  * @returns The updated feature or undefined if not found
 6437 |  */
 6438 | export function updateFeature(
 6439 |   id: string,
 6440 |   updatedFields: Partial<Omit<Feature, 'id' | 'createdAt'>>
 6441 | ): Feature | undefined {
 6442 |   const feature = features[id];
 6443 |   
 6444 |   if (!feature) {
 6445 |     return undefined;
 6446 |   }
 6447 |   
 6448 |   // Update the feature with new fields
 6449 |   const updatedFeature = {
 6450 |     ...feature,
 6451 |     ...updatedFields,
 6452 |     updatedAt: new Date()
 6453 |   };
 6454 |   
 6455 |   features[id] = updatedFeature;
 6456 |   return updatedFeature;
 6457 | }
 6458 | 
 6459 | /**
 6460 |  * List all features
 6461 |  * @returns Array of all features
 6462 |  */
 6463 | export function listFeatures(): Feature[] {
 6464 |   return Object.values(features);
 6465 | }
 6466 | 
 6467 | /**
 6468 |  * Delete a feature by ID
 6469 |  * @param id The feature ID
 6470 |  * @returns True if deleted, false if not found
 6471 |  */
 6472 | export function deleteFeature(id: string): boolean {
 6473 |   if (features[id]) {
 6474 |     delete features[id];
 6475 |     return true;
 6476 |   }
 6477 |   return false;
 6478 | }
 6479 | 
 6480 | ================
 6481 | File: src/test-mcp-improved.js
 6482 | ================
 6483 | #!/usr/bin/env node
 6484 | 
 6485 | /**
 6486 |  * @file test-mcp-improved.js
 6487 |  * 
 6488 |  * Test script for the improved MCP server implementation.
 6489 |  * Tests the tool registry, resource registry, and error handling.
 6490 |  */
 6491 | 
 6492 | const { spawn } = require('child_process');
 6493 | const path = require('path');
 6494 | 
 6495 | // Path to the MCP server
 6496 | const SERVER_PATH = path.join(__dirname, 'index-updated.ts');
 6497 | 
 6498 | // Store responses and state
 6499 | const responses = [];
 6500 | let featureId = null;
 6501 | 
 6502 | // Start the MCP server process
 6503 | const server = spawn('ts-node', [SERVER_PATH], {
 6504 |   stdio: ['pipe', 'pipe', process.stderr]
 6505 | });
 6506 | 
 6507 | // Handle server's stdout
 6508 | server.stdout.on('data', (data) => {
 6509 |   try {
 6510 |     const lines = data.toString().trim().split('\n');
 6511 |     for (const line of lines) {
 6512 |       if (!line.trim()) continue;
 6513 |       
 6514 |       // Parse the JSON response
 6515 |       const response = JSON.parse(line);
 6516 |       responses.push(response);
 6517 |       
 6518 |       // Process the response based on its type
 6519 |       processResponse(response);
 6520 |     }
 6521 |   } catch (error) {
 6522 |     console.error('Error processing server response:', error);
 6523 |   }
 6524 | });
 6525 | 
 6526 | // Process a server response
 6527 | function processResponse(response) {
 6528 |   if (response.id === 'init') {
 6529 |     sendInitialized();
 6530 |   } else if (response.id === 'start-feature') {
 6531 |     // Extract feature ID from the response
 6532 |     const content = response.result?.content[0]?.text;
 6533 |     if (content) {
 6534 |       const match = content.match(/Feature ID: ([a-z0-9-]+)/);
 6535 |       if (match) {
 6536 |         featureId = match[1];
 6537 |         console.log(`\nCreated feature with ID: ${featureId}`);
 6538 |         
 6539 |         // Ask the first clarification question
 6540 |         sendProvideClarification(featureId, 'What problem does this feature solve?', 'The feature solves the problem of managing test data across different environments.');
 6541 |       }
 6542 |     }
 6543 |   } else if (response.id === 'clarify-1') {
 6544 |     sendProvideClarification(featureId, 'Who are the target users?', 'Developers and QA engineers who need to create, manage, and share test data.');
 6545 |   } else if (response.id === 'clarify-2') {
 6546 |     sendProvideClarification(featureId, 'What are the key requirements?', 'Data import/export, version control integration, and user-friendly interface.');
 6547 |   } else if (response.id === 'clarify-3') {
 6548 |     sendProvideClarification(featureId, 'What are the success criteria?', 'Users can create and manage test data across environments with minimal effort.');
 6549 |   } else if (response.id === 'clarify-4') {
 6550 |     sendProvideClarification(featureId, 'Any technical constraints?', 'Must work with existing database systems and be containerizable.');
 6551 |   } else if (response.id === 'clarify-5') {
 6552 |     console.log('\nAll clarification questions answered.');
 6553 |     
 6554 |     // Generate PRD
 6555 |     sendGeneratePRD(featureId);
 6556 |   } else if (response.id === 'generate-prd') {
 6557 |     // Generate implementation plan
 6558 |     sendGenerateImplementationPlan(featureId);
 6559 |   } else if (response.id === 'generate-implementation-plan') {
 6560 |     // Create a phase
 6561 |     sendCreatePhase(featureId);
 6562 |   } else if (response.id === 'create-phase') {
 6563 |     // Extract phase ID from the response
 6564 |     const content = response.result?.content[0]?.text;
 6565 |     if (content) {
 6566 |       const match = content.match(/ID: ([a-z0-9-]+)/);
 6567 |       if (match) {
 6568 |         const phaseId = match[1];
 6569 |         console.log(`\nCreated phase with ID: ${phaseId}`);
 6570 |         
 6571 |         // Update phase status
 6572 |         sendUpdatePhaseStatus(featureId, phaseId, 'in_progress');
 6573 |       }
 6574 |     }
 6575 |   } else if (response.id === 'update-phase-status') {
 6576 |     // Get feature details
 6577 |     sendReadResource(`feature://${featureId}`);
 6578 |   } else if (response.id === 'read-feature') {
 6579 |     // Test resource handler
 6580 |     sendReadResource(`feature://${featureId}/progress`);
 6581 |   } else if (response.id === 'read-progress') {
 6582 |     // Test list resources
 6583 |     sendListResources();
 6584 |   } else if (response.id === 'list-resources') {
 6585 |     // Test list tools
 6586 |     sendListTools();
 6587 |   } else if (response.id === 'list-tools') {
 6588 |     // All tests completed
 6589 |     console.log('\nAll tests completed successfully.');
 6590 |     
 6591 |     // Clean up
 6592 |     server.stdin.end();
 6593 |     process.exit(0);
 6594 |   }
 6595 | }
 6596 | 
 6597 | // Send initialization message
 6598 | function sendInitialize() {
 6599 |   const message = {
 6600 |     jsonrpc: '2.0',
 6601 |     id: 'init',
 6602 |     method: 'initialize',
 6603 |     params: {
 6604 |       processId: process.pid,
 6605 |       clientInfo: {
 6606 |         name: 'MCP Test Client',
 6607 |         version: '1.0.0'
 6608 |       },
 6609 |       capabilities: {
 6610 |         resources: {},
 6611 |         tools: {},
 6612 |         prompts: {}
 6613 |       }
 6614 |     }
 6615 |   };
 6616 |   
 6617 |   sendMessage(message);
 6618 | }
 6619 | 
 6620 | // Send initialized notification
 6621 | function sendInitialized() {
 6622 |   const message = {
 6623 |     jsonrpc: '2.0',
 6624 |     method: 'initialized',
 6625 |     params: {}
 6626 |   };
 6627 |   
 6628 |   sendMessage(message);
 6629 |   
 6630 |   // Start the tests after initialization
 6631 |   console.log('\nStarting tests...');
 6632 |   sendStartFeature();
 6633 | }
 6634 | 
 6635 | // Send a message to start feature clarification
 6636 | function sendStartFeature() {
 6637 |   const message = {
 6638 |     jsonrpc: '2.0',
 6639 |     id: 'start-feature',
 6640 |     method: 'callTool',
 6641 |     params: {
 6642 |       name: 'start_feature_clarification',
 6643 |       arguments: {
 6644 |         featureName: 'Test Data Manager',
 6645 |         initialDescription: 'A tool for managing test data across various environments.'
 6646 |       }
 6647 |     }
 6648 |   };
 6649 |   
 6650 |   sendMessage(message);
 6651 | }
 6652 | 
 6653 | // Send a message to provide clarification
 6654 | function sendProvideClarification(featureId, question, answer) {
 6655 |   // Use a different ID for each clarification to track them
 6656 |   const clarificationId = `clarify-${responses.filter(r => r.id && r.id.startsWith('clarify-')).length + 1}`;
 6657 |   
 6658 |   const message = {
 6659 |     jsonrpc: '2.0',
 6660 |     id: clarificationId,
 6661 |     method: 'callTool',
 6662 |     params: {
 6663 |       name: 'provide_clarification',
 6664 |       arguments: {
 6665 |         featureId,
 6666 |         question,
 6667 |         answer
 6668 |       }
 6669 |     }
 6670 |   };
 6671 |   
 6672 |   sendMessage(message);
 6673 | }
 6674 | 
 6675 | // Send a message to generate a PRD
 6676 | function sendGeneratePRD(featureId) {
 6677 |   const message = {
 6678 |     jsonrpc: '2.0',
 6679 |     id: 'generate-prd',
 6680 |     method: 'callTool',
 6681 |     params: {
 6682 |       name: 'generate_prd',
 6683 |       arguments: {
 6684 |         featureId
 6685 |       }
 6686 |     }
 6687 |   };
 6688 |   
 6689 |   sendMessage(message);
 6690 | }
 6691 | 
 6692 | // Send a message to generate an implementation plan
 6693 | function sendGenerateImplementationPlan(featureId) {
 6694 |   const message = {
 6695 |     jsonrpc: '2.0',
 6696 |     id: 'generate-implementation-plan',
 6697 |     method: 'callTool',
 6698 |     params: {
 6699 |       name: 'generate_implementation_plan',
 6700 |       arguments: {
 6701 |         featureId
 6702 |       }
 6703 |     }
 6704 |   };
 6705 |   
 6706 |   sendMessage(message);
 6707 | }
 6708 | 
 6709 | // Send a message to create a phase
 6710 | function sendCreatePhase(featureId) {
 6711 |   const message = {
 6712 |     jsonrpc: '2.0',
 6713 |     id: 'create-phase',
 6714 |     method: 'callTool',
 6715 |     params: {
 6716 |       name: 'create_phase',
 6717 |       arguments: {
 6718 |         featureId,
 6719 |         name: 'Design',
 6720 |         description: 'Design the architecture and user interface for the Test Data Manager.'
 6721 |       }
 6722 |     }
 6723 |   };
 6724 |   
 6725 |   sendMessage(message);
 6726 | }
 6727 | 
 6728 | // Send a message to update phase status
 6729 | function sendUpdatePhaseStatus(featureId, phaseId, status) {
 6730 |   const message = {
 6731 |     jsonrpc: '2.0',
 6732 |     id: 'update-phase-status',
 6733 |     method: 'callTool',
 6734 |     params: {
 6735 |       name: 'update_phase_status',
 6736 |       arguments: {
 6737 |         featureId,
 6738 |         phaseId,
 6739 |         status
 6740 |       }
 6741 |     }
 6742 |   };
 6743 |   
 6744 |   sendMessage(message);
 6745 | }
 6746 | 
 6747 | // Send a message to read a resource
 6748 | function sendReadResource(uri) {
 6749 |   const message = {
 6750 |     jsonrpc: '2.0',
 6751 |     id: uri.includes('progress') ? 'read-progress' : 'read-feature',
 6752 |     method: 'readResource',
 6753 |     params: {
 6754 |       uri
 6755 |     }
 6756 |   };
 6757 |   
 6758 |   sendMessage(message);
 6759 | }
 6760 | 
 6761 | // Send a message to list resources
 6762 | function sendListResources() {
 6763 |   const message = {
 6764 |     jsonrpc: '2.0',
 6765 |     id: 'list-resources',
 6766 |     method: 'listResources',
 6767 |     params: {}
 6768 |   };
 6769 |   
 6770 |   sendMessage(message);
 6771 | }
 6772 | 
 6773 | // Send a message to list tools
 6774 | function sendListTools() {
 6775 |   const message = {
 6776 |     jsonrpc: '2.0',
 6777 |     id: 'list-tools',
 6778 |     method: 'listTools',
 6779 |     params: {}
 6780 |   };
 6781 |   
 6782 |   sendMessage(message);
 6783 | }
 6784 | 
 6785 | // Send a message to the server
 6786 | function sendMessage(message) {
 6787 |   const json = JSON.stringify(message);
 6788 |   server.stdin.write(json + '\n');
 6789 | }
 6790 | 
 6791 | // Start the test
 6792 | sendInitialize();
 6793 | 
 6794 | // Handle process exit
 6795 | process.on('exit', () => {
 6796 |   server.kill();
 6797 | });
 6798 | 
 6799 | ================
 6800 | File: src/tool-handlers.ts
 6801 | ================
 6802 | /**
 6803 |  * @file tool-handlers.ts
 6804 |  * @version 1.0.0
 6805 |  * 
 6806 |  * Provides handlers for the MCP tools exposed by the Vibe-Coder MCP Server.
 6807 |  * These handlers are registered with the tool registry for consistent handling.
 6808 |  */
 6809 | 
 6810 | import { z } from 'zod';
 6811 | import { ToolHandler, toolRegistry } from './registry.js';
 6812 | import { getFeature, updateFeature } from './storage.js';
 6813 | import { 
 6814 |   getNextClarificationQuestion,
 6815 |   isClarificationComplete, 
 6816 |   getClarificationStatus 
 6817 | } from './clarification.js';
 6818 | import { 
 6819 |   generatePRD, 
 6820 |   generateImplementationPlan 
 6821 | } from './documentation.js';
 6822 | import {
 6823 |   createPhase,
 6824 |   updatePhaseStatus,
 6825 |   addTask,
 6826 |   updateTaskStatus
 6827 | } from './phases.js';
 6828 | import {
 6829 |   createFeatureObject
 6830 | } from './utils.js';
 6831 | import {
 6832 |   validateFeatureId,
 6833 |   validatePhaseId,
 6834 |   validateTaskId,
 6835 |   validateFeaturePhaseTask,
 6836 |   validateRequiredText,
 6837 |   validatePhaseStatusValue
 6838 | } from './validators.js';
 6839 | import { 
 6840 |   createToolErrorResponse, 
 6841 |   featureNotFoundError, 
 6842 |   phaseNotFoundError, 
 6843 |   taskNotFoundError, 
 6844 |   invalidPhaseTransitionError, 
 6845 |   clarificationIncompleteError 
 6846 | } from './errors.js';
 6847 | import { Phase, Task } from './types.js';
 6848 | 
 6849 | // Schema for start_feature_clarification
 6850 | const StartFeatureClarificationSchema = z.object({
 6851 |   featureName: z.string().min(2).max(100),
 6852 |   initialDescription: z.string().optional().default("")
 6853 | });
 6854 | 
 6855 | /**
 6856 |  * Start feature clarification handler
 6857 |  */
 6858 | const startFeatureClarificationHandler: ToolHandler<z.infer<typeof StartFeatureClarificationSchema>> = async (params) => {
 6859 |   try {
 6860 |     const { featureName, initialDescription } = StartFeatureClarificationSchema.parse(params);
 6861 |     
 6862 |     // Create a new feature
 6863 |     const feature = createFeatureObject(featureName, initialDescription);
 6864 |     updateFeature(feature.id, feature);
 6865 |     
 6866 |     // Get the first clarification question
 6867 |     const firstQuestion = getNextClarificationQuestion(feature);
 6868 |     
 6869 |     return {
 6870 |       content: [{
 6871 |         type: "text",
 6872 |         text: `Feature ID: ${feature.id}\n\nLet's clarify your feature request. ${firstQuestion}`
 6873 |       }]
 6874 |     };
 6875 |   } catch (error) {
 6876 |     if (error instanceof z.ZodError) {
 6877 |       const errorMessage = error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ');
 6878 |       return createToolErrorResponse(`Validation error: ${errorMessage}`);
 6879 |     }
 6880 |     return createToolErrorResponse(error instanceof Error ? error.message : "Unknown error");
 6881 |   }
 6882 | };
 6883 | 
 6884 | // Schema for provide_clarification
 6885 | const ProvideClarificationSchema = z.object({
 6886 |   featureId: z.string().min(1),
 6887 |   question: z.string().min(1),
 6888 |   answer: z.string().min(1)
 6889 | });
 6890 | 
 6891 | /**
 6892 |  * Provide clarification handler
 6893 |  */
 6894 | const provideClarificationHandler: ToolHandler<z.infer<typeof ProvideClarificationSchema>> = async (params) => {
 6895 |   try {
 6896 |     const { featureId, question, answer } = ProvideClarificationSchema.parse(params);
 6897 |     
 6898 |     console.log(`\n[CLARIFICATION] Received request for feature ${featureId}\n  Question: "${question.substring(0, 50)}..."\n  Answer: "${answer.substring(0, 50)}..."`);
 6899 |     
 6900 |     // Get the feature
 6901 |     const feature = getFeature(featureId);
 6902 |     if (!feature) {
 6903 |       console.log(`[CLARIFICATION] Feature ID ${featureId} not found`);
 6904 |       return featureNotFoundError(featureId);
 6905 |     }
 6906 |     
 6907 |     console.log(`[CLARIFICATION] Found feature: ${feature.name} with ${feature.clarificationResponses.length} existing responses`);
 6908 |     
 6909 |     // Add the clarification response to the feature
 6910 |     feature.clarificationResponses.push({
 6911 |       question,
 6912 |       answer,
 6913 |       timestamp: new Date()
 6914 |     });
 6915 |     
 6916 |     console.log(`[CLARIFICATION] Added response, now has ${feature.clarificationResponses.length} responses`);
 6917 |     
 6918 |     // Save the feature with the updated clarification response
 6919 |     updateFeature(featureId, feature);
 6920 |     
 6921 |     // Get the next question or indicate all questions are answered
 6922 |     const nextQuestion = getNextClarificationQuestion(feature);
 6923 |     
 6924 |     if (nextQuestion) {
 6925 |       // Check if nextQuestion is a string before using substring
 6926 |       const questionPreview = typeof nextQuestion === 'string' 
 6927 |         ? nextQuestion.substring(0, 50) + "..." 
 6928 |         : "All questions answered";
 6929 |       console.log(`[CLARIFICATION] Returning next question: "${questionPreview}"`);
 6930 |       return {
 6931 |         content: [{
 6932 |           type: "text",
 6933 |           text: `Response recorded. ${nextQuestion}`
 6934 |         }]
 6935 |       };
 6936 |     } else {
 6937 |       // All questions answered
 6938 |       console.log(`[CLARIFICATION] All questions answered`);
 6939 |       return {
 6940 |         content: [{
 6941 |           type: "text",
 6942 |           text: "All clarification questions have been answered. You can now generate a PRD for this feature."
 6943 |         }]
 6944 |       };
 6945 |     }
 6946 |   } catch (error) {
 6947 |     if (error instanceof z.ZodError) {
 6948 |       const errorMessage = error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ');
 6949 |       return createToolErrorResponse(`Validation error: ${errorMessage}`);
 6950 |     }
 6951 |     return createToolErrorResponse(error instanceof Error ? error.message : "Unknown error");
 6952 |   }
 6953 | };
 6954 | 
 6955 | // Schema for generate_prd
 6956 | const GeneratePrdSchema = z.object({
 6957 |   featureId: z.string().min(1)
 6958 | });
 6959 | 
 6960 | /**
 6961 |  * Generate PRD handler
 6962 |  */
 6963 | const generatePrdHandler: ToolHandler<z.infer<typeof GeneratePrdSchema>> = async (params) => {
 6964 |   try {
 6965 |     const { featureId } = GeneratePrdSchema.parse(params);
 6966 |     
 6967 |     // Validate feature ID
 6968 |     const featureResult = validateFeatureId(featureId);
 6969 |     if (!featureResult.valid) {
 6970 |       return createToolErrorResponse(featureResult.message);
 6971 |     }
 6972 |     
 6973 |     const feature = featureResult.data;
 6974 |     
 6975 |     // Check if clarifications are complete
 6976 |     if (!isClarificationComplete(feature)) {
 6977 |       return clarificationIncompleteError(getClarificationStatus(feature));
 6978 |     }
 6979 |     
 6980 |     // Generate PRD
 6981 |     const prdDoc = generatePRD(feature);
 6982 |     
 6983 |     // Store the document
 6984 |     feature.prdDoc = prdDoc;
 6985 |     updateFeature(featureId, feature);
 6986 |     
 6987 |     return {
 6988 |       content: [{
 6989 |         type: "text",
 6990 |         text: `PRD generated for feature ${feature.name}. You can view it using the resource URI: feature://${feature.id}/prd`
 6991 |       }]
 6992 |     };
 6993 |   } catch (error) {
 6994 |     if (error instanceof z.ZodError) {
 6995 |       const errorMessage = error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ');
 6996 |       return createToolErrorResponse(`Validation error: ${errorMessage}`);
 6997 |     }
 6998 |     return createToolErrorResponse(error instanceof Error ? error.message : "Unknown error");
 6999 |   }
 7000 | };
 7001 | 
 7002 | // Schema for generate_implementation_plan
 7003 | const GenerateImplementationPlanSchema = z.object({
 7004 |   featureId: z.string().min(1)
 7005 | });
 7006 | 
 7007 | /**
 7008 |  * Generate implementation plan handler
 7009 |  */
 7010 | const generateImplementationPlanHandler: ToolHandler<z.infer<typeof GenerateImplementationPlanSchema>> = async (params) => {
 7011 |   try {
 7012 |     const { featureId } = GenerateImplementationPlanSchema.parse(params);
 7013 |     
 7014 |     // Validate feature ID
 7015 |     const featureResult = validateFeatureId(featureId);
 7016 |     if (!featureResult.valid) {
 7017 |       return createToolErrorResponse(featureResult.message);
 7018 |     }
 7019 |     
 7020 |     const feature = featureResult.data;
 7021 |     
 7022 |     // Check if clarifications are complete
 7023 |     if (!isClarificationComplete(feature)) {
 7024 |       return clarificationIncompleteError(getClarificationStatus(feature));
 7025 |     }
 7026 |     
 7027 |     // Generate the implementation plan
 7028 |     const implDoc = generateImplementationPlan(feature);
 7029 |     
 7030 |     // Store the document
 7031 |     feature.implDoc = implDoc;
 7032 |     updateFeature(featureId, feature);
 7033 |     
 7034 |     return {
 7035 |       content: [{
 7036 |         type: "text",
 7037 |         text: `Implementation plan generated for feature ${feature.name}. You can view it using the resource URI: feature://${feature.id}/implementation`
 7038 |       }]
 7039 |     };
 7040 |   } catch (error) {
 7041 |     if (error instanceof z.ZodError) {
 7042 |       const errorMessage = error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ');
 7043 |       return createToolErrorResponse(`Validation error: ${errorMessage}`);
 7044 |     }
 7045 |     return createToolErrorResponse(error instanceof Error ? error.message : "Unknown error");
 7046 |   }
 7047 | };
 7048 | 
 7049 | // Schema for create_phase
 7050 | const CreatePhaseSchema = z.object({
 7051 |   featureId: z.string().min(1),
 7052 |   name: z.string().min(2).max(100),
 7053 |   description: z.string().min(1)
 7054 | });
 7055 | 
 7056 | /**
 7057 |  * Create phase handler
 7058 |  */
 7059 | const createPhaseHandler: ToolHandler<z.infer<typeof CreatePhaseSchema>> = async (params) => {
 7060 |   try {
 7061 |     const { featureId, name, description } = CreatePhaseSchema.parse(params);
 7062 |     
 7063 |     // Validate feature ID
 7064 |     const featureResult = validateFeatureId(featureId);
 7065 |     if (!featureResult.valid) {
 7066 |       return createToolErrorResponse(featureResult.message);
 7067 |     }
 7068 |     
 7069 |     const feature = featureResult.data;
 7070 |     
 7071 |     // Create the phase
 7072 |     const phase = createPhase(featureId, name, description);
 7073 |     
 7074 |     if (!phase) {
 7075 |       return createToolErrorResponse(`Failed to create phase for feature ${feature.name}`);
 7076 |     }
 7077 |     
 7078 |     return {
 7079 |       content: [{
 7080 |         type: "text",
 7081 |         text: `Phase "${name}" created with ID: ${phase.id}`
 7082 |       }]
 7083 |     };
 7084 |   } catch (error) {
 7085 |     if (error instanceof z.ZodError) {
 7086 |       const errorMessage = error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ');
 7087 |       return createToolErrorResponse(`Validation error: ${errorMessage}`);
 7088 |     }
 7089 |     return createToolErrorResponse(error instanceof Error ? error.message : "Unknown error");
 7090 |   }
 7091 | };
 7092 | 
 7093 | // Schema for update_phase_status
 7094 | const UpdatePhaseStatusSchema = z.object({
 7095 |   featureId: z.string().min(1),
 7096 |   phaseId: z.string().min(1),
 7097 |   status: z.enum(["pending", "in_progress", "completed", "reviewed"])
 7098 | });
 7099 | 
 7100 | /**
 7101 |  * Update phase status handler
 7102 |  */
 7103 | const updatePhaseStatusHandler: ToolHandler<z.infer<typeof UpdatePhaseStatusSchema>> = async (params) => {
 7104 |   try {
 7105 |     const { featureId, phaseId, status } = UpdatePhaseStatusSchema.parse(params);
 7106 |     
 7107 |     // Validate feature and phase
 7108 |     const validationResult = validateFeaturePhaseTask(featureId, phaseId);
 7109 |     if (!validationResult.valid) {
 7110 |       return createToolErrorResponse(validationResult.message);
 7111 |     }
 7112 |     
 7113 |     const { feature, phase } = validationResult.data;
 7114 |     
 7115 |     // Validate the status transition
 7116 |     const transitionResult = phase.status !== status; 
 7117 |     if (!transitionResult) {
 7118 |       return invalidPhaseTransitionError(phase.status, status);
 7119 |     }
 7120 |     
 7121 |     // Update the phase status
 7122 |     const updatedPhase = updatePhaseStatus(featureId, phaseId, status);
 7123 |     
 7124 |     return {
 7125 |       content: [{
 7126 |         type: "text",
 7127 |         text: `Phase status updated to "${status}"`
 7128 |       }]
 7129 |     };
 7130 |   } catch (error) {
 7131 |     if (error instanceof z.ZodError) {
 7132 |       const errorMessage = error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ');
 7133 |       return createToolErrorResponse(`Validation error: ${errorMessage}`);
 7134 |     }
 7135 |     return createToolErrorResponse(error instanceof Error ? error.message : "Unknown error");
 7136 |   }
 7137 | };
 7138 | 
 7139 | // Schema for add_task
 7140 | const AddTaskSchema = z.object({
 7141 |   featureId: z.string().min(1),
 7142 |   phaseId: z.string().min(1),
 7143 |   description: z.string().min(3).max(500)
 7144 | });
 7145 | 
 7146 | /**
 7147 |  * Add task handler
 7148 |  */
 7149 | const addTaskHandler: ToolHandler<z.infer<typeof AddTaskSchema>> = async (params) => {
 7150 |   try {
 7151 |     const { featureId, phaseId, description } = AddTaskSchema.parse(params);
 7152 |     
 7153 |     // Validate feature and phase
 7154 |     const validationResult = validateFeaturePhaseTask(featureId, phaseId);
 7155 |     if (!validationResult.valid) {
 7156 |       return createToolErrorResponse(validationResult.message);
 7157 |     }
 7158 |     
 7159 |     const { feature, phase } = validationResult.data;
 7160 |     
 7161 |     // Add the task
 7162 |     const taskId = addTask(featureId, phaseId, description);
 7163 |     
 7164 |     return {
 7165 |       content: [{
 7166 |         type: "text",
 7167 |         text: `Task added to phase "${phase.name}" with ID: ${taskId}`
 7168 |       }]
 7169 |     };
 7170 |   } catch (error) {
 7171 |     if (error instanceof z.ZodError) {
 7172 |       const errorMessage = error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ');
 7173 |       return createToolErrorResponse(`Validation error: ${errorMessage}`);
 7174 |     }
 7175 |     return createToolErrorResponse(error instanceof Error ? error.message : "Unknown error");
 7176 |   }
 7177 | };
 7178 | 
 7179 | // Schema for update_task_status
 7180 | const UpdateTaskStatusSchema = z.object({
 7181 |   featureId: z.string().min(1),
 7182 |   phaseId: z.string().min(1),
 7183 |   taskId: z.string().min(1),
 7184 |   completed: z.boolean()
 7185 | });
 7186 | 
 7187 | /**
 7188 |  * Update task status handler
 7189 |  */
 7190 | const updateTaskStatusHandler: ToolHandler<z.infer<typeof UpdateTaskStatusSchema>> = async (params) => {
 7191 |   try {
 7192 |     const { featureId, phaseId, taskId, completed } = UpdateTaskStatusSchema.parse(params);
 7193 |     
 7194 |     // Validate feature, phase and task
 7195 |     const validationResult = validateFeaturePhaseTask(featureId, phaseId, taskId);
 7196 |     if (!validationResult.valid) {
 7197 |       return createToolErrorResponse(validationResult.message);
 7198 |     }
 7199 |     
 7200 |     const { feature, phase, task } = validationResult.data;
 7201 |     
 7202 |     // Update the task status
 7203 |     const updatedTask = updateTaskStatus(featureId, phaseId, taskId, completed);
 7204 |     
 7205 |     // Check if all tasks in this phase are now completed
 7206 |     if (completed && phase.tasks.every((t: Task) => t.id === taskId || t.completed)) {
 7207 |       // Auto-advance the phase to 'completed' status
 7208 |       return {
 7209 |         content: [{
 7210 |           type: "text",
 7211 |           text: `Task marked as ${completed ? 'completed' : 'incomplete'}. All tasks in this phase are now complete. The phase "${phase.name}" has been automatically marked as completed.`
 7212 |         }]
 7213 |       };
 7214 |     }
 7215 |     
 7216 |     // Check if all tasks are completed and suggest phase update if applicable
 7217 |     let message = `Task status updated to ${completed ? 'completed' : 'not completed'}`;
 7218 |     
 7219 |     if (completed && phase.tasks.every((t: Task) => t.id === taskId || t.completed)) {
 7220 |       // All tasks are now completed
 7221 |       message += `. All tasks in phase ${phase.name} are now completed. Consider updating the phase status to 'completed'.`;
 7222 |     }
 7223 |     
 7224 |     return {
 7225 |       content: [{
 7226 |         type: "text",
 7227 |         text: message
 7228 |       }]
 7229 |     };
 7230 |   } catch (error) {
 7231 |     if (error instanceof z.ZodError) {
 7232 |       const errorMessage = error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ');
 7233 |       return createToolErrorResponse(`Validation error: ${errorMessage}`);
 7234 |     }
 7235 |     return createToolErrorResponse(error instanceof Error ? error.message : "Unknown error");
 7236 |   }
 7237 | };
 7238 | 
 7239 | // Schema for get_next_phase_action
 7240 | const GetNextPhaseActionSchema = z.object({
 7241 |   featureId: z.string().min(1)
 7242 | });
 7243 | 
 7244 | /**
 7245 |  * Get next phase action handler
 7246 |  */
 7247 | const getNextPhaseActionHandler: ToolHandler<z.infer<typeof GetNextPhaseActionSchema>> = async (params) => {
 7248 |   try {
 7249 |     const { featureId } = GetNextPhaseActionSchema.parse(params);
 7250 |     
 7251 |     // Validate feature ID
 7252 |     const featureResult = validateFeatureId(featureId);
 7253 |     if (!featureResult.valid) {
 7254 |       return createToolErrorResponse(featureResult.message);
 7255 |     }
 7256 |     
 7257 |     const feature = featureResult.data;
 7258 |     
 7259 |     // Find the current active phase (first non-completed/reviewed phase)
 7260 |     const currentPhase = feature.phases.find((p: Phase) => p.status === 'pending' || p.status === 'in_progress');
 7261 |     
 7262 |     if (!currentPhase) {
 7263 |       // All phases are completed or reviewed
 7264 |       return {
 7265 |         content: [{
 7266 |           type: "text",
 7267 |           text: 'All phases are completed or reviewed. The feature implementation is done!'
 7268 |         }]
 7269 |       };
 7270 |     }
 7271 |     
 7272 |     // Check task completion status
 7273 |     const completedTasks = currentPhase.tasks.filter((t: Task) => t.completed);
 7274 |     const pendingTasks = currentPhase.tasks.filter((t: Task) => !t.completed);
 7275 |     
 7276 |     // Determine next action based on phase and task status
 7277 |     let message = '';
 7278 |     
 7279 |     if (currentPhase.status === 'pending') {
 7280 |       message = `Phase "${currentPhase.name}" is pending. Start working on this phase by setting its status to "in_progress".`;
 7281 |     } else if (currentPhase.status === 'in_progress') {
 7282 |       if (pendingTasks.length > 0) {
 7283 |         message = `${completedTasks.length}/${currentPhase.tasks.length} tasks are completed in phase "${currentPhase.name}". Continue working on pending tasks.`;
 7284 |       } else if (currentPhase.tasks.length === 0) {
 7285 |         message = `Phase "${currentPhase.name}" has no tasks defined. Add tasks or mark the phase as completed if appropriate.`;
 7286 |       } else {
 7287 |         // All tasks are completed
 7288 |         message = `All tasks in phase "${currentPhase.name}" are completed. Consider marking this phase as completed.`;
 7289 |       }
 7290 |     }
 7291 |     
 7292 |     return {
 7293 |       content: [{
 7294 |         type: "text",
 7295 |         text: message
 7296 |       }]
 7297 |     };
 7298 |   } catch (error) {
 7299 |     if (error instanceof z.ZodError) {
 7300 |       const errorMessage = error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ');
 7301 |       return createToolErrorResponse(`Validation error: ${errorMessage}`);
 7302 |     }
 7303 |     return createToolErrorResponse(error instanceof Error ? error.message : "Unknown error");
 7304 |   }
 7305 | };
 7306 | 
 7307 | /**
 7308 |  * Register all tool handlers with the tool registry
 7309 |  */
 7310 | export function registerToolHandlers() {
 7311 |   toolRegistry.register(
 7312 |     'start_feature_clarification', 
 7313 |     startFeatureClarificationHandler,
 7314 |     'Start the clarification process for a new feature',
 7315 |     {
 7316 |       type: "object",
 7317 |       properties: {
 7318 |         featureName: {
 7319 |           type: "string",
 7320 |           description: "Name of the feature"
 7321 |         },
 7322 |         initialDescription: {
 7323 |           type: "string",
 7324 |           description: "Initial description of the feature"
 7325 |         }
 7326 |       },
 7327 |       required: ["featureName"]
 7328 |     },
 7329 |     [
 7330 |       {
 7331 |         featureName: "User Authentication",
 7332 |         initialDescription: "Add login and registration functionality to the application"
 7333 |       },
 7334 |       {
 7335 |         featureName: "Data Export",
 7336 |         initialDescription: "Allow users to export their data in CSV and JSON formats"
 7337 |       }
 7338 |     ]
 7339 |   );
 7340 | 
 7341 |   toolRegistry.register(
 7342 |     'provide_clarification', 
 7343 |     provideClarificationHandler,
 7344 |     'Provide answer to a clarification question',
 7345 |     {
 7346 |       type: "object",
 7347 |       properties: {
 7348 |         featureId: {
 7349 |           type: "string",
 7350 |           description: "ID of the feature"
 7351 |         },
 7352 |         question: {
 7353 |           type: "string",
 7354 |           description: "Clarification question"
 7355 |         },
 7356 |         answer: {
 7357 |           type: "string",
 7358 |           description: "Answer to the clarification question"
 7359 |         }
 7360 |       },
 7361 |       required: ["featureId", "question", "answer"]
 7362 |     },
 7363 |     [
 7364 |       {
 7365 |         featureId: "feature-123",
 7366 |         question: "What problem does this feature solve?",
 7367 |         answer: "This feature solves the problem of users forgetting their passwords by providing a secure password reset flow."
 7368 |       },
 7369 |       {
 7370 |         featureId: "feature-456",
 7371 |         question: "Who are the target users?",
 7372 |         answer: "The target users are administrators who need to manage user accounts and permissions."
 7373 |       }
 7374 |     ]
 7375 |   );
 7376 | 
 7377 |   toolRegistry.register(
 7378 |     'generate_prd', 
 7379 |     generatePrdHandler,
 7380 |     'Generate a PRD document based on clarification responses',
 7381 |     {
 7382 |       type: "object",
 7383 |       properties: {
 7384 |         featureId: {
 7385 |           type: "string",
 7386 |           description: "ID of the feature"
 7387 |         }
 7388 |       },
 7389 |       required: ["featureId"]
 7390 |     },
 7391 |     [
 7392 |       { featureId: "feature-123" }
 7393 |     ]
 7394 |   );
 7395 | 
 7396 |   toolRegistry.register(
 7397 |     'generate_implementation_plan', 
 7398 |     generateImplementationPlanHandler,
 7399 |     'Generate an implementation plan for a feature based on clarifications and PRD',
 7400 |     {
 7401 |       type: 'object',
 7402 |       properties: {
 7403 |         featureId: {
 7404 |           type: 'string',
 7405 |           description: 'The ID of the feature to generate an implementation plan for'
 7406 |         }
 7407 |       },
 7408 |       required: ['featureId']
 7409 |     }
 7410 |   );
 7411 | 
 7412 |   toolRegistry.register(
 7413 |     'create_phase', 
 7414 |     createPhaseHandler,
 7415 |     'Create a new development phase for a feature',
 7416 |     {
 7417 |       type: 'object',
 7418 |       properties: {
 7419 |         featureId: {
 7420 |           type: 'string',
 7421 |           description: 'ID of the feature to create a phase for'
 7422 |         },
 7423 |         name: {
 7424 |           type: 'string',
 7425 |           description: 'Name of the phase'
 7426 |         },
 7427 |         description: {
 7428 |           type: 'string',
 7429 |           description: 'Description of the phase'
 7430 |         }
 7431 |       },
 7432 |       required: ['featureId', 'name', 'description']
 7433 |     },
 7434 |     [
 7435 |       {
 7436 |         featureId: "feature-123",
 7437 |         name: "Requirements Analysis",
 7438 |         description: "Gather and analyze requirements for the feature"
 7439 |       },
 7440 |       {
 7441 |         featureId: "feature-123",
 7442 |         name: "Implementation",
 7443 |         description: "Implement the core functionality of the feature"
 7444 |       }
 7445 |     ]
 7446 |   );
 7447 | 
 7448 |   toolRegistry.register(
 7449 |     'update_phase_status', 
 7450 |     updatePhaseStatusHandler,
 7451 |     'Update the status of a development phase',
 7452 |     {
 7453 |       type: 'object',
 7454 |       properties: {
 7455 |         featureId: {
 7456 |           type: 'string',
 7457 |           description: 'ID of the feature containing the phase'
 7458 |         },
 7459 |         phaseId: {
 7460 |           type: 'string',
 7461 |           description: 'ID of the phase to update'
 7462 |         },
 7463 |         status: {
 7464 |           type: 'string',
 7465 |           description: 'New status for the phase (pending, in_progress, completed, reviewed)'
 7466 |         }
 7467 |       },
 7468 |       required: ['featureId', 'phaseId', 'status']
 7469 |     },
 7470 |     [
 7471 |       {
 7472 |         featureId: "feature-123",
 7473 |         phaseId: "phase-456",
 7474 |         status: "in_progress"
 7475 |       },
 7476 |       {
 7477 |         featureId: "feature-123",
 7478 |         phaseId: "phase-456",
 7479 |         status: "completed"
 7480 |       }
 7481 |     ]
 7482 |   );
 7483 | 
 7484 |   toolRegistry.register(
 7485 |     'add_task', 
 7486 |     addTaskHandler,
 7487 |     'Add a task to a development phase',
 7488 |     {
 7489 |       type: 'object',
 7490 |       properties: {
 7491 |         featureId: {
 7492 |           type: 'string',
 7493 |           description: 'ID of the feature containing the phase'
 7494 |         },
 7495 |         phaseId: {
 7496 |           type: 'string',
 7497 |           description: 'ID of the phase to add the task to'
 7498 |         },
 7499 |         description: {
 7500 |           type: 'string',
 7501 |           description: 'Description of the task'
 7502 |         }
 7503 |       },
 7504 |       required: ['featureId', 'phaseId', 'description']
 7505 |     },
 7506 |     [
 7507 |       {
 7508 |         featureId: "feature-123",
 7509 |         phaseId: "phase-456",
 7510 |         description: "Create database migration scripts"
 7511 |       },
 7512 |       {
 7513 |         featureId: "feature-123",
 7514 |         phaseId: "phase-456",
 7515 |         description: "Implement user interface components"
 7516 |       }
 7517 |     ]
 7518 |   );
 7519 | 
 7520 |   toolRegistry.register(
 7521 |     'update_task_status', 
 7522 |     updateTaskStatusHandler,
 7523 |     'Update the completion status of a task',
 7524 |     {
 7525 |       type: 'object',
 7526 |       properties: {
 7527 |         featureId: {
 7528 |           type: 'string',
 7529 |           description: 'ID of the feature containing the phase'
 7530 |         },
 7531 |         phaseId: {
 7532 |           type: 'string',
 7533 |           description: 'ID of the phase containing the task'
 7534 |         },
 7535 |         taskId: {
 7536 |           type: 'string',
 7537 |           description: 'ID of the task to update'
 7538 |         },
 7539 |         completed: {
 7540 |           type: 'boolean',
 7541 |           description: 'Whether the task is completed'
 7542 |         }
 7543 |       },
 7544 |       required: ['featureId', 'phaseId', 'taskId', 'completed']
 7545 |     },
 7546 |     [
 7547 |       {
 7548 |         featureId: "feature-123",
 7549 |         phaseId: "phase-456",
 7550 |         taskId: "task-789",
 7551 |         completed: true
 7552 |       },
 7553 |       {
 7554 |         featureId: "feature-123",
 7555 |         phaseId: "phase-456",
 7556 |         taskId: "task-789",
 7557 |         completed: false
 7558 |       }
 7559 |     ]
 7560 |   );
 7561 | 
 7562 |   toolRegistry.register(
 7563 |     'get_next_phase_action', 
 7564 |     getNextPhaseActionHandler,
 7565 |     'Get guidance on what to do next in the current phase or whether to move to the next phase',
 7566 |     {
 7567 |       type: 'object',
 7568 |       properties: {
 7569 |         featureId: {
 7570 |           type: 'string',
 7571 |           description: 'ID of the feature'
 7572 |         }
 7573 |       },
 7574 |       required: ['featureId']
 7575 |     },
 7576 |     [
 7577 |       { featureId: "feature-123" }
 7578 |     ]
 7579 |   );
 7580 | }
 7581 | 
 7582 | // Export all handlers for testing or direct usage
 7583 | export {
 7584 |   startFeatureClarificationHandler,
 7585 |   provideClarificationHandler,
 7586 |   generatePrdHandler,
 7587 |   generateImplementationPlanHandler,
 7588 |   createPhaseHandler,
 7589 |   updatePhaseStatusHandler,
 7590 |   addTaskHandler,
 7591 |   updateTaskStatusHandler,
 7592 |   getNextPhaseActionHandler
 7593 | };
 7594 | 
 7595 | ================
 7596 | File: src/types.ts
 7597 | ================
 7598 | /**
 7599 |  * Core data types for the Vibe-Coder MCP Server
 7600 |  */
 7601 | 
 7602 | /**
 7603 |  * Represents a feature being developed
 7604 |  */
 7605 | export type Feature = {
 7606 |   id: string;
 7607 |   name: string;
 7608 |   description: string;
 7609 |   clarificationResponses: ClarificationResponse[];
 7610 |   prd?: string;
 7611 |   prdDoc?: string;
 7612 |   implementationPlan?: string;
 7613 |   implDoc?: string;
 7614 |   phases: Phase[];
 7615 |   createdAt: Date;
 7616 |   updatedAt: Date;
 7617 | };
 7618 | 
 7619 | /**
 7620 |  * Represents a question and answer pair from the clarification process
 7621 |  */
 7622 | export type ClarificationResponse = {
 7623 |   question: string;
 7624 |   answer: string;
 7625 |   timestamp: Date;
 7626 | };
 7627 | 
 7628 | /**
 7629 |  * Represents a development phase within a feature
 7630 |  */
 7631 | export type Phase = {
 7632 |   id: string;
 7633 |   name: string;
 7634 |   description: string;
 7635 |   tasks: Task[];
 7636 |   status: PhaseStatus;
 7637 |   createdAt: Date;
 7638 |   updatedAt: Date;
 7639 | };
 7640 | 
 7641 | /**
 7642 |  * Possible statuses for a development phase
 7643 |  */
 7644 | export type PhaseStatus = "pending" | "in_progress" | "completed" | "reviewed";
 7645 | 
 7646 | /**
 7647 |  * Represents a task within a development phase
 7648 |  */
 7649 | export type Task = {
 7650 |   id: string;
 7651 |   description: string;
 7652 |   completed: boolean;
 7653 |   createdAt: Date;
 7654 |   updatedAt: Date;
 7655 | };
 7656 | 
 7657 | /**
 7658 |  * Storage interface for features
 7659 |  */
 7660 | export interface FeatureStorage {
 7661 |   [id: string]: Feature;
 7662 | }
 7663 | 
 7664 | ================
 7665 | File: src/utils.ts
 7666 | ================
 7667 | /**
 7668 |  * @file utils.ts
 7669 |  * @version 1.1.0
 7670 |  * 
 7671 |  * Utility functions for the Vibe-Coder MCP Server
 7672 |  */
 7673 | 
 7674 | import { Feature, Phase, Task, PhaseStatus } from './types.js';
 7675 | import { FeatureId, PhaseId, TaskId, createFeatureId, createPhaseId, createTaskId } from './schemas.js';
 7676 | 
 7677 | /**
 7678 |  * Generate a unique ID for features with proper prefix
 7679 |  * @returns A feature ID string
 7680 |  */
 7681 | export function generateFeatureId(): FeatureId {
 7682 |   const randomPart = Math.random().toString(36).substring(2, 10);
 7683 |   return createFeatureId(`feature-${randomPart}`);
 7684 | }
 7685 | 
 7686 | /**
 7687 |  * Generate a unique ID for phases with proper prefix
 7688 |  * @returns A phase ID string
 7689 |  */
 7690 | export function generatePhaseId(): PhaseId {
 7691 |   const randomPart = Math.random().toString(36).substring(2, 10);
 7692 |   return createPhaseId(`phase-${randomPart}`);
 7693 | }
 7694 | 
 7695 | /**
 7696 |  * Generate a unique ID for tasks with proper prefix
 7697 |  * @returns A task ID string
 7698 |  */
 7699 | export function generateTaskId(): TaskId {
 7700 |   const randomPart = Math.random().toString(36).substring(2, 10);
 7701 |   return createTaskId(`task-${randomPart}`);
 7702 | }
 7703 | 
 7704 | /**
 7705 |  * Legacy ID generator for backward compatibility
 7706 |  * @deprecated Use the typed ID generators instead
 7707 |  * @returns A random string ID
 7708 |  */
 7709 | export function generateId(): string {
 7710 |   return Math.random().toString(36).substring(2, 15) + 
 7711 |          Math.random().toString(36).substring(2, 15);
 7712 | }
 7713 | 
 7714 | /**
 7715 |  * Format a date to ISO string without milliseconds
 7716 |  * @param date The date to format
 7717 |  * @returns Formatted date string
 7718 |  */
 7719 | export function formatDate(date: Date): string {
 7720 |   return date.toISOString().split('.')[0] + 'Z';
 7721 | }
 7722 | 
 7723 | /**
 7724 |  * Create a new timestamp
 7725 |  * @returns Current date
 7726 |  */
 7727 | export function now(): Date {
 7728 |   return new Date();
 7729 | }
 7730 | 
 7731 | /**
 7732 |  * Create a default feature object with the given name and description
 7733 |  * @param name The feature name
 7734 |  * @param description The feature description
 7735 |  * @returns A new feature object
 7736 |  */
 7737 | export function createFeatureObject(name: string, description: string = ""): Feature {
 7738 |   const timestamp = now();
 7739 |   
 7740 |   return {
 7741 |     id: generateFeatureId(),
 7742 |     name,
 7743 |     description,
 7744 |     clarificationResponses: [],
 7745 |     phases: [],
 7746 |     createdAt: timestamp,
 7747 |     updatedAt: timestamp
 7748 |   };
 7749 | }
 7750 | 
 7751 | /**
 7752 |  * Create a default phase object with the given name and description
 7753 |  * @param name The phase name
 7754 |  * @param description The phase description
 7755 |  * @returns A new phase object
 7756 |  */
 7757 | export function createPhaseObject(name: string, description: string): Phase {
 7758 |   const timestamp = now();
 7759 |   
 7760 |   return {
 7761 |     id: generatePhaseId(),
 7762 |     name,
 7763 |     description,
 7764 |     tasks: [],
 7765 |     status: "pending" as PhaseStatus,
 7766 |     createdAt: timestamp,
 7767 |     updatedAt: timestamp
 7768 |   };
 7769 | }
 7770 | 
 7771 | /**
 7772 |  * Create a default task object with the given description
 7773 |  * @param description The task description
 7774 |  * @returns A new task object
 7775 |  */
 7776 | export function createTaskObject(description: string): Task {
 7777 |   const timestamp = now();
 7778 |   
 7779 |   return {
 7780 |     id: generateTaskId(),
 7781 |     description,
 7782 |     completed: false,
 7783 |     createdAt: timestamp,
 7784 |     updatedAt: timestamp
 7785 |   };
 7786 | }
 7787 | 
 7788 | /**
 7789 |  * Validate if a status is a valid phase status
 7790 |  * @param status The status to validate
 7791 |  * @returns True if valid, false otherwise
 7792 |  */
 7793 | export function isValidPhaseStatus(status: string): boolean {
 7794 |   return ['pending', 'in_progress', 'completed', 'reviewed'].includes(status);
 7795 | }
 7796 | 
 7797 | /**
 7798 |  * Generate a detailed progress summary for a feature
 7799 |  * @param feature The feature to generate a summary for
 7800 |  * @returns A formatted string with the feature's progress details
 7801 |  */
 7802 | export function generateFeatureProgressSummary(feature: Feature): string {
 7803 |   const totalPhases = feature.phases.length;
 7804 |   const completedPhases = feature.phases.filter(p => p.status === 'completed' || p.status === 'reviewed').length;
 7805 |   const inProgressPhases = feature.phases.filter(p => p.status === 'in_progress').length;
 7806 |   
 7807 |   const totalTasks = feature.phases.reduce((acc, phase) => acc + phase.tasks.length, 0);
 7808 |   const completedTasks = feature.phases.reduce(
 7809 |     (acc, phase) => acc + phase.tasks.filter(t => t.completed).length, 0
 7810 |   );
 7811 |   
 7812 |   const phaseProgress = totalPhases > 0 
 7813 |     ? Math.round((completedPhases / totalPhases) * 100) 
 7814 |     : 0;
 7815 |     
 7816 |   const taskProgress = totalTasks > 0 
 7817 |     ? Math.round((completedTasks / totalTasks) * 100) 
 7818 |     : 0;
 7819 |   
 7820 |   let summary = `
 7821 | # Feature Progress: ${feature.name}
 7822 | 
 7823 | ## Overview
 7824 | - Feature ID: ${feature.id}
 7825 | - Created: ${feature.createdAt.toISOString()}
 7826 | - Last Updated: ${feature.updatedAt.toISOString()}
 7827 | - Description: ${feature.description}
 7828 | 
 7829 | ## Progress Summary
 7830 | - Phases: ${completedPhases}/${totalPhases} completed (${phaseProgress}%)
 7831 | - Tasks: ${completedTasks}/${totalTasks} completed (${taskProgress}%)
 7832 | - Phases in Progress: ${inProgressPhases}
 7833 | 
 7834 | ## Phase Details
 7835 | `;
 7836 | 
 7837 |   if (totalPhases === 0) {
 7838 |     summary += "\nNo phases defined for this feature yet.";
 7839 |   } else {
 7840 |     feature.phases.forEach(phase => {
 7841 |       const phaseTasks = phase.tasks.length;
 7842 |       const phaseCompletedTasks = phase.tasks.filter(t => t.completed).length;
 7843 |       const phaseTaskProgress = phaseTasks > 0 
 7844 |         ? Math.round((phaseCompletedTasks / phaseTasks) * 100) 
 7845 |         : 0;
 7846 |       
 7847 |       summary += `
 7848 | ### ${phase.name} (${phase.status})
 7849 | - ID: ${phase.id}
 7850 | - Progress: ${phaseCompletedTasks}/${phaseTasks} tasks (${phaseTaskProgress}%)
 7851 | - Description: ${phase.description}
 7852 | 
 7853 | Tasks:
 7854 | ${phase.tasks.map(task => `- [${task.completed ? 'x' : ' '}] ${task.description}`).join('\n')}
 7855 | `;
 7856 |     });
 7857 |   }
 7858 |   
 7859 |   return summary;
 7860 | }
 7861 | 
 7862 | ================
 7863 | File: src/validators.ts
 7864 | ================
 7865 | /**
 7866 |  * @file validators.ts
 7867 |  * @version 1.0.0
 7868 |  * 
 7869 |  * Provides validation utilities for the Vibe-Coder MCP Server tools.
 7870 |  * These validators ensure that tool inputs are valid and provide consistent
 7871 |  * error handling across all tools.
 7872 |  */
 7873 | 
 7874 | import { Feature, Phase, Task, PhaseStatus } from './types.js';
 7875 | import { getFeature } from './storage.js';
 7876 | import { isValidPhaseStatus } from './utils.js';
 7877 | 
 7878 | /**
 7879 |  * Standard validation result type
 7880 |  */
 7881 | export type ValidationResult = {
 7882 |   valid: boolean;
 7883 |   message: string;
 7884 |   data?: any; // Optional validated data
 7885 | };
 7886 | 
 7887 | /**
 7888 |  * Validate feature ID and return the feature if valid
 7889 |  * @param featureId The feature ID to validate
 7890 |  * @returns Validation result with feature in data if valid
 7891 |  */
 7892 | export function validateFeatureId(featureId: string): ValidationResult {
 7893 |   // Check if feature ID is provided
 7894 |   if (!featureId || featureId.trim() === '') {
 7895 |     return {
 7896 |       valid: false,
 7897 |       message: 'Feature ID is required'
 7898 |     };
 7899 |   }
 7900 | 
 7901 |   // Check if feature exists
 7902 |   const feature = getFeature(featureId);
 7903 |   if (!feature) {
 7904 |     return {
 7905 |       valid: false,
 7906 |       message: `Feature with ID ${featureId} not found`
 7907 |     };
 7908 |   }
 7909 | 
 7910 |   return {
 7911 |     valid: true,
 7912 |     message: 'Feature is valid',
 7913 |     data: feature
 7914 |   };
 7915 | }
 7916 | 
 7917 | /**
 7918 |  * Validate phase ID in the context of a feature
 7919 |  * @param feature The feature containing the phase
 7920 |  * @param phaseId The phase ID to validate
 7921 |  * @returns Validation result with phase in data if valid
 7922 |  */
 7923 | export function validatePhaseId(feature: Feature, phaseId: string): ValidationResult {
 7924 |   // Check if phase ID is provided
 7925 |   if (!phaseId || phaseId.trim() === '') {
 7926 |     return {
 7927 |       valid: false,
 7928 |       message: 'Phase ID is required'
 7929 |     };
 7930 |   }
 7931 | 
 7932 |   // Check if phase exists in feature
 7933 |   const phase = feature.phases.find(p => p.id === phaseId);
 7934 |   if (!phase) {
 7935 |     return {
 7936 |       valid: false,
 7937 |       message: `Phase with ID ${phaseId} not found in feature ${feature.name}`
 7938 |     };
 7939 |   }
 7940 | 
 7941 |   return {
 7942 |     valid: true,
 7943 |     message: 'Phase is valid',
 7944 |     data: phase
 7945 |   };
 7946 | }
 7947 | 
 7948 | /**
 7949 |  * Validate task ID in the context of a phase
 7950 |  * @param phase The phase containing the task
 7951 |  * @param taskId The task ID to validate
 7952 |  * @returns Validation result with task in data if valid
 7953 |  */
 7954 | export function validateTaskId(phase: Phase, taskId: string): ValidationResult {
 7955 |   // Check if task ID is provided
 7956 |   if (!taskId || taskId.trim() === '') {
 7957 |     return {
 7958 |       valid: false,
 7959 |       message: 'Task ID is required'
 7960 |     };
 7961 |   }
 7962 | 
 7963 |   // Check if task exists in phase
 7964 |   const task = phase.tasks.find(t => t.id === taskId);
 7965 |   if (!task) {
 7966 |     return {
 7967 |       valid: false,
 7968 |       message: `Task with ID ${taskId} not found in phase ${phase.name}`
 7969 |     };
 7970 |   }
 7971 | 
 7972 |   return {
 7973 |     valid: true,
 7974 |     message: 'Task is valid',
 7975 |     data: task
 7976 |   };
 7977 | }
 7978 | 
 7979 | /**
 7980 |  * Validate phase status
 7981 |  * @param status The status to validate
 7982 |  * @returns Validation result
 7983 |  */
 7984 | export function validatePhaseStatusValue(status: string): ValidationResult {
 7985 |   if (!status || status.trim() === '') {
 7986 |     return {
 7987 |       valid: false,
 7988 |       message: 'Phase status is required'
 7989 |     };
 7990 |   }
 7991 | 
 7992 |   if (!isValidPhaseStatus(status)) {
 7993 |     return {
 7994 |       valid: false,
 7995 |       message: `Invalid phase status: ${status}. Valid values are: pending, in_progress, completed, reviewed`
 7996 |     };
 7997 |   }
 7998 | 
 7999 |   return {
 8000 |     valid: true,
 8001 |     message: 'Phase status is valid',
 8002 |     data: status as PhaseStatus
 8003 |   };
 8004 | }
 8005 | 
 8006 | /**
 8007 |  * Validate required text field
 8008 |  * @param value The text value
 8009 |  * @param fieldName The name of the field for error messages
 8010 |  * @param minLength Minimum allowed length
 8011 |  * @param maxLength Maximum allowed length
 8012 |  * @returns Validation result
 8013 |  */
 8014 | export function validateRequiredText(
 8015 |   value: string,
 8016 |   fieldName: string,
 8017 |   minLength: number = 1,
 8018 |   maxLength: number = 1000
 8019 | ): ValidationResult {
 8020 |   if (!value || value.trim() === '') {
 8021 |     return {
 8022 |       valid: false,
 8023 |       message: `${fieldName} is required`
 8024 |     };
 8025 |   }
 8026 | 
 8027 |   if (value.length < minLength) {
 8028 |     return {
 8029 |       valid: false,
 8030 |       message: `${fieldName} must be at least ${minLength} characters`
 8031 |     };
 8032 |   }
 8033 | 
 8034 |   if (value.length > maxLength) {
 8035 |     return {
 8036 |       valid: false,
 8037 |       message: `${fieldName} must be no more than ${maxLength} characters`
 8038 |     };
 8039 |   }
 8040 | 
 8041 |   return {
 8042 |     valid: true,
 8043 |     message: `${fieldName} is valid`,
 8044 |     data: value.trim()
 8045 |   };
 8046 | }
 8047 | 
 8048 | /**
 8049 |  * Validate feature, phase, and task IDs together
 8050 |  * @param featureId Feature ID
 8051 |  * @param phaseId Phase ID
 8052 |  * @param taskId Task ID (optional)
 8053 |  * @returns Validation result with feature, phase, and task in data if valid
 8054 |  */
 8055 | export function validateFeaturePhaseTask(
 8056 |   featureId: string,
 8057 |   phaseId: string,
 8058 |   taskId?: string
 8059 | ): ValidationResult {
 8060 |   // Validate feature
 8061 |   const featureResult = validateFeatureId(featureId);
 8062 |   if (!featureResult.valid) {
 8063 |     return featureResult;
 8064 |   }
 8065 | 
 8066 |   // Validate phase
 8067 |   const phaseResult = validatePhaseId(featureResult.data, phaseId);
 8068 |   if (!phaseResult.valid) {
 8069 |     return phaseResult;
 8070 |   }
 8071 | 
 8072 |   // If taskId is provided, validate it
 8073 |   if (taskId) {
 8074 |     const taskResult = validateTaskId(phaseResult.data, taskId);
 8075 |     if (!taskResult.valid) {
 8076 |       return taskResult;
 8077 |     }
 8078 | 
 8079 |     return {
 8080 |       valid: true,
 8081 |       message: 'Feature, phase, and task are valid',
 8082 |       data: {
 8083 |         feature: featureResult.data,
 8084 |         phase: phaseResult.data,
 8085 |         task: taskResult.data
 8086 |       }
 8087 |     };
 8088 |   }
 8089 | 
 8090 |   return {
 8091 |     valid: true,
 8092 |     message: 'Feature and phase are valid',
 8093 |     data: {
 8094 |       feature: featureResult.data,
 8095 |       phase: phaseResult.data
 8096 |     }
 8097 |   };
 8098 | }
 8099 | 
 8100 | ================
 8101 | File: .gitignore
 8102 | ================
 8103 | node_modules/
 8104 | build/
 8105 | *.log
 8106 | .env*
 8107 | 
 8108 | ================
 8109 | File: debug.js
 8110 | ================
 8111 | #!/usr/bin/env node
 8112 | 
 8113 | // This file is just for inspecting the features state
 8114 | // Since we can't access the runtime state directly, 
 8115 | // we'll examine how the clarification functions work
 8116 | 
 8117 | import { getNextClarificationQuestion, DEFAULT_CLARIFICATION_QUESTIONS } from './build/clarification.js';
 8118 | 
 8119 | console.log('Default questions:', DEFAULT_CLARIFICATION_QUESTIONS);
 8120 | 
 8121 | // Test the function with a mock feature
 8122 | const mockFeature = {
 8123 |   id: 'test',
 8124 |   clarificationResponses: []
 8125 | };
 8126 | 
 8127 | console.log('Initial question:', getNextClarificationQuestion(mockFeature));
 8128 | 
 8129 | // Add a response and check next question
 8130 | mockFeature.clarificationResponses.push({
 8131 |   question: DEFAULT_CLARIFICATION_QUESTIONS[0],
 8132 |   answer: 'Test answer',
 8133 |   timestamp: new Date()
 8134 | });
 8135 | 
 8136 | console.log('After 1 response, next question:', getNextClarificationQuestion(mockFeature));
 8137 | 
 8138 | // Add another response
 8139 | mockFeature.clarificationResponses.push({
 8140 |   question: DEFAULT_CLARIFICATION_QUESTIONS[1],
 8141 |   answer: 'Test answer 2',
 8142 |   timestamp: new Date()
 8143 | });
 8144 | 
 8145 | console.log('After 2 responses, next question:', getNextClarificationQuestion(mockFeature));
 8146 | 
 8147 | ================
 8148 | File: MCP-docs.txt
 8149 | ================
 8150 | # Example Clients
 8151 | Source: https://modelcontextprotocol.io/clients
 8152 | 
 8153 | A list of applications that support MCP integrations
 8154 | 
 8155 | This page provides an overview of applications that support the Model Context Protocol (MCP). Each client may support different MCP features, allowing for varying levels of integration with MCP servers.
 8156 | 
 8157 | ## Feature support matrix
 8158 | 
 8159 | | Client                               | [Resources] | [Prompts] | [Tools] | [Sampling] | Roots | Notes                                                              |
 8160 | | ------------------------------------ | ----------- | --------- | ------- | ---------- | ----- | ------------------------------------------------------------------ |
 8161 | | [Claude Desktop App][Claude]         | ✅           | ✅         | ✅       | ❌          | ❌     | Full support for all MCP features                                  |
 8162 | | [5ire][5ire]                         | ❌           | ❌         | ✅       | ❌          | ❌     | Supports tools.                                                    |
 8163 | | [BeeAI Framework][BeeAI Framework]   | ❌           | ❌         | ✅       | ❌          | ❌     | Supports tools in agentic workflows.                               |
 8164 | | [Cline][Cline]                       | ✅           | ❌         | ✅       | ❌          | ❌     | Supports tools and resources.                                      |
 8165 | | [Continue][Continue]                 | ✅           | ✅         | ✅       | ❌          | ❌     | Full support for all MCP features                                  |
 8166 | | [Cursor][Cursor]                     | ❌           | ❌         | ✅       | ❌          | ❌     | Supports tools.                                                    |
 8167 | | [Emacs Mcp][Mcp.el]                  | ❌           | ❌         | ✅       | ❌          | ❌     | Supports tools in Emacs.                                           |
 8168 | | [Firebase Genkit][Genkit]            | ⚠️          | ✅         | ✅       | ❌          | ❌     | Supports resource list and lookup through tools.                   |
 8169 | | [GenAIScript][GenAIScript]           | ❌           | ❌         | ✅       | ❌          | ❌     | Supports tools.                                                    |
 8170 | | [Goose][Goose]                       | ❌           | ❌         | ✅       | ❌          | ❌     | Supports tools.                                                    |
 8171 | | [LibreChat][LibreChat]               | ❌           | ❌         | ✅       | ❌          | ❌     | Supports tools for Agents                                          |
 8172 | | [mcp-agent][mcp-agent]               | ❌           | ❌         | ✅       | ⚠️         | ❌     | Supports tools, server connection management, and agent workflows. |
 8173 | | [oterm][oterm]                       | ❌           | ❌         | ✅       | ❌          | ❌     | Supports tools.                                                    |
 8174 | | [Roo Code][Roo Code]                 | ✅           | ❌         | ✅       | ❌          | ❌     | Supports tools and resources.                                      |
 8175 | | [Sourcegraph Cody][Cody]             | ✅           | ❌         | ❌       | ❌          | ❌     | Supports resources through OpenCTX                                 |
 8176 | | [Superinterface][Superinterface]     | ❌           | ❌         | ✅       | ❌          | ❌     | Supports tools                                                     |
 8177 | | [TheiaAI/TheiaIDE][TheiaAI/TheiaIDE] | ❌           | ❌         | ✅       | ❌          | ❌     | Supports tools for Agents in Theia AI and the AI-powered Theia IDE |
 8178 | | [Windsurf Editor][Windsurf]          | ❌           | ❌         | ✅       | ❌          | ❌     | Supports tools with AI Flow for collaborative development.         |
 8179 | | [Zed][Zed]                           | ❌           | ✅         | ❌       | ❌          | ❌     | Prompts appear as slash commands                                   |
 8180 | | [SpinAI][SpinAI]                     | ❌           | ❌         | ✅       | ❌          | ❌     | Supports tools for Typescript AI Agents                            |
 8181 | | [OpenSumi][OpenSumi]                 | ❌           | ❌         | ✅       | ❌          | ❌     | Supports tools in OpenSumi                                         |
 8182 | | [Daydreams Agents][Daydreams]        | ✅           | ✅         | ✅       | ❌          | ❌     | Support for drop in Servers to Daydreams agents                    |
 8183 | 
 8184 | [Claude]: https://claude.ai/download
 8185 | 
 8186 | [Cursor]: https://cursor.com
 8187 | 
 8188 | [Zed]: https://zed.dev
 8189 | 
 8190 | [Cody]: https://sourcegraph.com/cody
 8191 | 
 8192 | [Genkit]: https://github.com/firebase/genkit
 8193 | 
 8194 | [Continue]: https://github.com/continuedev/continue
 8195 | 
 8196 | [GenAIScript]: https://microsoft.github.io/genaiscript/reference/scripts/mcp-tools/
 8197 | 
 8198 | [Cline]: https://github.com/cline/cline
 8199 | 
 8200 | [LibreChat]: https://github.com/danny-avila/LibreChat
 8201 | 
 8202 | [TheiaAI/TheiaIDE]: https://eclipsesource.com/blogs/2024/12/19/theia-ide-and-theia-ai-support-mcp/
 8203 | 
 8204 | [Superinterface]: https://superinterface.ai
 8205 | 
 8206 | [5ire]: https://github.com/nanbingxyz/5ire
 8207 | 
 8208 | [BeeAI Framework]: https://i-am-bee.github.io/beeai-framework
 8209 | 
 8210 | [mcp-agent]: https://github.com/lastmile-ai/mcp-agent
 8211 | 
 8212 | [Mcp.el]: https://github.com/lizqwerscott/mcp.el
 8213 | 
 8214 | [Roo Code]: https://roocode.com
 8215 | 
 8216 | [Goose]: https://block.github.io/goose/docs/goose-architecture/#interoperability-with-extensions
 8217 | 
 8218 | [Windsurf]: https://codeium.com/windsurf
 8219 | 
 8220 | [Daydreams]: https://github.com/daydreamsai/daydreams
 8221 | 
 8222 | [SpinAI]: https://spinai.dev
 8223 | 
 8224 | [OpenSumi]: https://github.com/opensumi/core
 8225 | 
 8226 | [oterm]: https://github.com/ggozad/oterm
 8227 | 
 8228 | [Resources]: https://modelcontextprotocol.io/docs/concepts/resources
 8229 | 
 8230 | [Prompts]: https://modelcontextprotocol.io/docs/concepts/prompts
 8231 | 
 8232 | [Tools]: https://modelcontextprotocol.io/docs/concepts/tools
 8233 | 
 8234 | [Sampling]: https://modelcontextprotocol.io/docs/concepts/sampling
 8235 | 
 8236 | ## Client details
 8237 | 
 8238 | ### Claude Desktop App
 8239 | 
 8240 | The Claude desktop application provides comprehensive support for MCP, enabling deep integration with local tools and data sources.
 8241 | 
 8242 | **Key features:**
 8243 | 
 8244 | * Full support for resources, allowing attachment of local files and data
 8245 | * Support for prompt templates
 8246 | * Tool integration for executing commands and scripts
 8247 | * Local server connections for enhanced privacy and security
 8248 | 
 8249 | > ⓘ Note: The Claude.ai web application does not currently support MCP. MCP features are only available in the desktop application.
 8250 | 
 8251 | ### 5ire
 8252 | 
 8253 | [5ire](https://github.com/nanbingxyz/5ire) is an open source cross-platform desktop AI assistant that supports tools through MCP servers.
 8254 | 
 8255 | **Key features:**
 8256 | 
 8257 | * Built-in MCP servers can be quickly enabled and disabled.
 8258 | * Users can add more servers by modifying the configuration file.
 8259 | * It is open-source and user-friendly, suitable for beginners.
 8260 | * Future support for MCP will be continuously improved.
 8261 | 
 8262 | ### BeeAI Framework
 8263 | 
 8264 | [BeeAI Framework](https://i-am-bee.github.io/beeai-framework) is an open-source framework for building, deploying, and serving powerful agentic workflows at scale. The framework includes the **MCP Tool**, a native feature that simplifies the integration of MCP servers into agentic workflows.
 8265 | 
 8266 | **Key features:**
 8267 | 
 8268 | * Seamlessly incorporate MCP tools into agentic workflows.
 8269 | * Quickly instantiate framework-native tools from connected MCP client(s).
 8270 | * Planned future support for agentic MCP capabilities.
 8271 | 
 8272 | **Learn more:**
 8273 | 
 8274 | * [Example of using MCP tools in agentic workflow](https://i-am-bee.github.io/beeai-framework/#/typescript/tools?id=using-the-mcptool-class)
 8275 | 
 8276 | ### Cline
 8277 | 
 8278 | [Cline](https://github.com/cline/cline) is an autonomous coding agent in VS Code that edits files, runs commands, uses a browser, and more–with your permission at each step.
 8279 | 
 8280 | **Key features:**
 8281 | 
 8282 | * Create and add tools through natural language (e.g. "add a tool that searches the web")
 8283 | * Share custom MCP servers Cline creates with others via the `~/Documents/Cline/MCP` directory
 8284 | * Displays configured MCP servers along with their tools, resources, and any error logs
 8285 | 
 8286 | ### Continue
 8287 | 
 8288 | [Continue](https://github.com/continuedev/continue) is an open-source AI code assistant, with built-in support for all MCP features.
 8289 | 
 8290 | **Key features**
 8291 | 
 8292 | * Type "@" to mention MCP resources
 8293 | * Prompt templates surface as slash commands
 8294 | * Use both built-in and MCP tools directly in chat
 8295 | * Supports VS Code and JetBrains IDEs, with any LLM
 8296 | 
 8297 | ### Cursor
 8298 | 
 8299 | [Cursor](https://docs.cursor.com/advanced/model-context-protocol) is an AI code editor.
 8300 | 
 8301 | **Key Features**:
 8302 | 
 8303 | * Support for MCP tools in Cursor Composer
 8304 | * Support for both STDIO and SSE
 8305 | 
 8306 | ### Emacs Mcp
 8307 | 
 8308 | [Emacs Mcp](https://github.com/lizqwerscott/mcp.el) is an Emacs client designed to interface with MCP servers, enabling seamless connections and interactions. It provides MCP tool invocation support for AI plugins like [gptel](https://github.com/karthink/gptel) and [llm](https://github.com/ahyatt/llm), adhering to Emacs' standard tool invocation format. This integration enhances the functionality of AI tools within the Emacs ecosystem.
 8309 | 
 8310 | **Key features:**
 8311 | 
 8312 | * Provides MCP tool support for Emacs.
 8313 | 
 8314 | ### Firebase Genkit
 8315 | 
 8316 | [Genkit](https://github.com/firebase/genkit) is Firebase's SDK for building and integrating GenAI features into applications. The [genkitx-mcp](https://github.com/firebase/genkit/tree/main/js/plugins/mcp) plugin enables consuming MCP servers as a client or creating MCP servers from Genkit tools and prompts.
 8317 | 
 8318 | **Key features:**
 8319 | 
 8320 | * Client support for tools and prompts (resources partially supported)
 8321 | * Rich discovery with support in Genkit's Dev UI playground
 8322 | * Seamless interoperability with Genkit's existing tools and prompts
 8323 | * Works across a wide variety of GenAI models from top providers
 8324 | 
 8325 | ### GenAIScript
 8326 | 
 8327 | Programmatically assemble prompts for LLMs using [GenAIScript](https://microsoft.github.io/genaiscript/) (in JavaScript). Orchestrate LLMs, tools, and data in JavaScript.
 8328 | 
 8329 | **Key features:**
 8330 | 
 8331 | * JavaScript toolbox to work with prompts
 8332 | * Abstraction to make it easy and productive
 8333 | * Seamless Visual Studio Code integration
 8334 | 
 8335 | ### Goose
 8336 | 
 8337 | [Goose](https://github.com/block/goose) is an open source AI agent that supercharges your software development by automating coding tasks.
 8338 | 
 8339 | **Key features:**
 8340 | 
 8341 | * Expose MCP functionality to Goose through tools.
 8342 | * MCPs can be installed directly via the [extensions directory](https://block.github.io/goose/v1/extensions/), CLI, or UI.
 8343 | * Goose allows you to extend its functionality by [building your own MCP servers](https://block.github.io/goose/docs/tutorials/custom-extensions).
 8344 | * Includes built-in tools for development, web scraping, automation, memory, and integrations with JetBrains and Google Drive.
 8345 | 
 8346 | ### LibreChat
 8347 | 
 8348 | [LibreChat](https://github.com/danny-avila/LibreChat) is an open-source, customizable AI chat UI that supports multiple AI providers, now including MCP integration.
 8349 | 
 8350 | **Key features:**
 8351 | 
 8352 | * Extend current tool ecosystem, including [Code Interpreter](https://www.librechat.ai/docs/features/code_interpreter) and Image generation tools, through MCP servers
 8353 | * Add tools to customizable [Agents](https://www.librechat.ai/docs/features/agents), using a variety of LLMs from top providers
 8354 | * Open-source and self-hostable, with secure multi-user support
 8355 | * Future roadmap includes expanded MCP feature support
 8356 | 
 8357 | ### mcp-agent
 8358 | 
 8359 | [mcp-agent] is a simple, composable framework to build agents using Model Context Protocol.
 8360 | 
 8361 | **Key features:**
 8362 | 
 8363 | * Automatic connection management of MCP servers.
 8364 | * Expose tools from multiple servers to an LLM.
 8365 | * Implements every pattern defined in [Building Effective Agents](https://www.anthropic.com/research/building-effective-agents).
 8366 | * Supports workflow pause/resume signals, such as waiting for human feedback.
 8367 | 
 8368 | ### oterm
 8369 | 
 8370 | [oterm] is a terminal client for Ollama allowing users to create chats/agents.
 8371 | 
 8372 | **Key features:**
 8373 | 
 8374 | * Support for multiple fully customizable chat sessions with Ollama connected with tools.
 8375 | * Support for MCP tools.
 8376 | 
 8377 | ### Roo Code
 8378 | 
 8379 | [Roo Code](https://roocode.com) enables AI coding assistance via MCP.
 8380 | 
 8381 | **Key features:**
 8382 | 
 8383 | * Support for MCP tools and resources
 8384 | * Integration with development workflows
 8385 | * Extensible AI capabilities
 8386 | 
 8387 | ### Sourcegraph Cody
 8388 | 
 8389 | [Cody](https://openctx.org/docs/providers/modelcontextprotocol) is Sourcegraph's AI coding assistant, which implements MCP through OpenCTX.
 8390 | 
 8391 | **Key features:**
 8392 | 
 8393 | * Support for MCP resources
 8394 | * Integration with Sourcegraph's code intelligence
 8395 | * Uses OpenCTX as an abstraction layer
 8396 | * Future support planned for additional MCP features
 8397 | 
 8398 | ### SpinAI
 8399 | 
 8400 | [SpinAI](https://spinai.dev) is an open-source TypeScript framework for building observable AI agents. The framework provides native MCP compatibility, allowing agents to seamlessly integrate with MCP servers and tools.
 8401 | 
 8402 | **Key features:**
 8403 | 
 8404 | * Built-in MCP compatibility for AI agents
 8405 | * Open-source TypeScript framework
 8406 | * Observable agent architecture
 8407 | * Native support for MCP tools integration
 8408 | 
 8409 | ### Superinterface
 8410 | 
 8411 | [Superinterface](https://superinterface.ai) is AI infrastructure and a developer platform to build in-app AI assistants with support for MCP, interactive components, client-side function calling and more.
 8412 | 
 8413 | **Key features:**
 8414 | 
 8415 | * Use tools from MCP servers in assistants embedded via React components or script tags
 8416 | * SSE transport support
 8417 | * Use any AI model from any AI provider (OpenAI, Anthropic, Ollama, others)
 8418 | 
 8419 | ### TheiaAI/TheiaIDE
 8420 | 
 8421 | [Theia AI](https://eclipsesource.com/blogs/2024/10/07/introducing-theia-ai/) is a framework for building AI-enhanced tools and IDEs. The [AI-powered Theia IDE](https://eclipsesource.com/blogs/2024/10/08/introducting-ai-theia-ide/) is an open and flexible development environment built on Theia AI.
 8422 | 
 8423 | **Key features:**
 8424 | 
 8425 | * **Tool Integration**: Theia AI enables AI agents, including those in the Theia IDE, to utilize MCP servers for seamless tool interaction.
 8426 | * **Customizable Prompts**: The Theia IDE allows users to define and adapt prompts, dynamically integrating MCP servers for tailored workflows.
 8427 | * **Custom agents**: The Theia IDE supports creating custom agents that leverage MCP capabilities, enabling users to design dedicated workflows on the fly.
 8428 | 
 8429 | Theia AI and Theia IDE's MCP integration provide users with flexibility, making them powerful platforms for exploring and adapting MCP.
 8430 | 
 8431 | **Learn more:**
 8432 | 
 8433 | * [Theia IDE and Theia AI MCP Announcement](https://eclipsesource.com/blogs/2024/12/19/theia-ide-and-theia-ai-support-mcp/)
 8434 | * [Download the AI-powered Theia IDE](https://theia-ide.org/)
 8435 | 
 8436 | ### Windsurf Editor
 8437 | 
 8438 | [Windsurf Editor](https://codeium.com/windsurf) is an agentic IDE that combines AI assistance with developer workflows. It features an innovative AI Flow system that enables both collaborative and independent AI interactions while maintaining developer control.
 8439 | 
 8440 | **Key features:**
 8441 | 
 8442 | * Revolutionary AI Flow paradigm for human-AI collaboration
 8443 | * Intelligent code generation and understanding
 8444 | * Rich development tools with multi-model support
 8445 | 
 8446 | ### Zed
 8447 | 
 8448 | [Zed](https://zed.dev/docs/assistant/model-context-protocol) is a high-performance code editor with built-in MCP support, focusing on prompt templates and tool integration.
 8449 | 
 8450 | **Key features:**
 8451 | 
 8452 | * Prompt templates surface as slash commands in the editor
 8453 | * Tool integration for enhanced coding workflows
 8454 | * Tight integration with editor features and workspace context
 8455 | * Does not support MCP resources
 8456 | 
 8457 | ### OpenSumi
 8458 | 
 8459 | [OpenSumi](https://github.com/opensumi/core) is a framework helps you quickly build AI Native IDE products.
 8460 | 
 8461 | **Key features:**
 8462 | 
 8463 | * Supports MCP tools in OpenSumi
 8464 | * Supports built-in IDE MCP servers and custom MCP servers
 8465 | 
 8466 | ### Daydreams
 8467 | 
 8468 | [Daydreams](https://github.com/daydreamsai/daydreams) is a generative agent framework for executing anything onchain
 8469 | 
 8470 | **Key features:**
 8471 | 
 8472 | * Supports MCP Servers in config
 8473 | * Exposes MCP Client
 8474 | 
 8475 | ## Adding MCP support to your application
 8476 | 
 8477 | If you've added MCP support to your application, we encourage you to submit a pull request to add it to this list. MCP integration can provide your users with powerful contextual AI capabilities and make your application part of the growing MCP ecosystem.
 8478 | 
 8479 | Benefits of adding MCP support:
 8480 | 
 8481 | * Enable users to bring their own context and tools
 8482 | * Join a growing ecosystem of interoperable AI applications
 8483 | * Provide users with flexible integration options
 8484 | * Support local-first AI workflows
 8485 | 
 8486 | To get started with implementing MCP in your application, check out our [Python](https://github.com/modelcontextprotocol/python-sdk) or [TypeScript SDK Documentation](https://github.com/modelcontextprotocol/typescript-sdk)
 8487 | 
 8488 | ## Updates and corrections
 8489 | 
 8490 | This list is maintained by the community. If you notice any inaccuracies or would like to update information about MCP support in your application, please submit a pull request or [open an issue in our documentation repository](https://github.com/modelcontextprotocol/docs/issues).
 8491 | 
 8492 | 
 8493 | # Contributing
 8494 | Source: https://modelcontextprotocol.io/development/contributing
 8495 | 
 8496 | How to participate in Model Context Protocol development
 8497 | 
 8498 | We welcome contributions from the community! Please review our [contributing guidelines](https://github.com/modelcontextprotocol/.github/blob/main/CONTRIBUTING.md) for details on how to submit changes.
 8499 | 
 8500 | All contributors must adhere to our [Code of Conduct](https://github.com/modelcontextprotocol/.github/blob/main/CODE_OF_CONDUCT.md).
 8501 | 
 8502 | For questions and discussions, please use [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions).
 8503 | 
 8504 | 
 8505 | # Roadmap
 8506 | Source: https://modelcontextprotocol.io/development/roadmap
 8507 | 
 8508 | Our plans for evolving Model Context Protocol (H1 2025)
 8509 | 
 8510 | The Model Context Protocol is rapidly evolving. This page outlines our current thinking on key priorities and future direction for **the first half of 2025**, though these may change significantly as the project develops.
 8511 | 
 8512 | <Note>The ideas presented here are not commitments—we may solve these challenges differently than described, or some may not materialize at all. This is also not an *exhaustive* list; we may incorporate work that isn't mentioned here.</Note>
 8513 | 
 8514 | We encourage community participation! Each section links to relevant discussions where you can learn more and contribute your thoughts.
 8515 | 
 8516 | ## Remote MCP Support
 8517 | 
 8518 | Our top priority is improving [remote MCP connections](https://github.com/modelcontextprotocol/specification/discussions/112), allowing clients to securely connect to MCP servers over the internet. Key initiatives include:
 8519 | 
 8520 | * [**Authentication & Authorization**](https://github.com/modelcontextprotocol/specification/discussions/64): Adding standardized auth capabilities, particularly focused on OAuth 2.0 support.
 8521 | 
 8522 | * [**Service Discovery**](https://github.com/modelcontextprotocol/specification/discussions/69): Defining how clients can discover and connect to remote MCP servers.
 8523 | 
 8524 | * [**Stateless Operations**](https://github.com/modelcontextprotocol/specification/discussions/102): Thinking about whether MCP could encompass serverless environments too, where they will need to be mostly stateless.
 8525 | 
 8526 | ## Reference Implementations
 8527 | 
 8528 | To help developers build with MCP, we want to offer documentation for:
 8529 | 
 8530 | * **Client Examples**: Comprehensive reference client implementation(s), demonstrating all protocol features
 8531 | * **Protocol Drafting**: Streamlined process for proposing and incorporating new protocol features
 8532 | 
 8533 | ## Distribution & Discovery
 8534 | 
 8535 | Looking ahead, we're exploring ways to make MCP servers more accessible. Some areas we may investigate include:
 8536 | 
 8537 | * **Package Management**: Standardized packaging format for MCP servers
 8538 | * **Installation Tools**: Simplified server installation across MCP clients
 8539 | * **Sandboxing**: Improved security through server isolation
 8540 | * **Server Registry**: A common directory for discovering available MCP servers
 8541 | 
 8542 | ## Agent Support
 8543 | 
 8544 | We're expanding MCP's capabilities for [complex agentic workflows](https://github.com/modelcontextprotocol/specification/discussions/111), particularly focusing on:
 8545 | 
 8546 | * [**Hierarchical Agent Systems**](https://github.com/modelcontextprotocol/specification/discussions/94): Improved support for trees of agents through namespacing and topology awareness.
 8547 | 
 8548 | * [**Interactive Workflows**](https://github.com/modelcontextprotocol/specification/issues/97): Better handling of user permissions and information requests across agent hierarchies, and ways to send output to users instead of models.
 8549 | 
 8550 | * [**Streaming Results**](https://github.com/modelcontextprotocol/specification/issues/117): Real-time updates from long-running agent operations.
 8551 | 
 8552 | ## Broader Ecosystem
 8553 | 
 8554 | We're also invested in:
 8555 | 
 8556 | * **Community-Led Standards Development**: Fostering a collaborative ecosystem where all AI providers can help shape MCP as an open standard through equal participation and shared governance, ensuring it meets the needs of diverse AI applications and use cases.
 8557 | * [**Additional Modalities**](https://github.com/modelcontextprotocol/specification/discussions/88): Expanding beyond text to support audio, video, and other formats.
 8558 | * \[**Standardization**] Considering standardization through a standardization body.
 8559 | 
 8560 | ## Get Involved
 8561 | 
 8562 | We welcome community participation in shaping MCP's future. Visit our [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions) to join the conversation and contribute your ideas.
 8563 | 
 8564 | 
 8565 | # What's New
 8566 | Source: https://modelcontextprotocol.io/development/updates
 8567 | 
 8568 | The latest updates and improvements to MCP
 8569 | 
 8570 | <Update label="2025-02-14" description="Java SDK released">
 8571 |   * We're excited to announce that the Java SDK developed by Spring AI at VMware Tanzu is now
 8572 |     the official [Java SDK](https://github.com/modelcontextprotocol/java-sdk) for MCP.
 8573 |     This joins our existing Kotlin SDK in our growing list of supported languages.
 8574 |     The Spring AI team will maintain the SDK as an integral part of the Model Context Protocol
 8575 |     organization. We're thrilled to welcome them to the MCP community!
 8576 | </Update>
 8577 | 
 8578 | <Update label="2025-01-27" description="Python SDK 1.2.1">
 8579 |   * Version [1.2.1](https://github.com/modelcontextprotocol/python-sdk/releases/tag/v1.2.1) of the MCP Python SDK has been released,
 8580 |     delivering important stability improvements and bug fixes.
 8581 | </Update>
 8582 | 
 8583 | <Update label="2025-01-18" description="SDK and Server Improvements">
 8584 |   * Simplified, express-like API in the [TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk)
 8585 |   * Added 8 new clients to the [clients page](https://modelcontextprotocol.io/clients)
 8586 | </Update>
 8587 | 
 8588 | <Update label="2025-01-03" description="SDK and Server Improvements">
 8589 |   * FastMCP API in the [Python SDK](https://github.com/modelcontextprotocol/python-sdk)
 8590 |   * Dockerized MCP servers in the [servers repo](https://github.com/modelcontextprotocol/servers)
 8591 | </Update>
 8592 | 
 8593 | <Update label="2024-12-21" description="Kotlin SDK released">
 8594 |   * Jetbrains released a Kotlin SDK for MCP!
 8595 |   * For a sample MCP Kotlin server, check out [this repository](https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/kotlin-mcp-server)
 8596 | </Update>
 8597 | 
 8598 | 
 8599 | # Core architecture
 8600 | Source: https://modelcontextprotocol.io/docs/concepts/architecture
 8601 | 
 8602 | Understand how MCP connects clients, servers, and LLMs
 8603 | 
 8604 | The Model Context Protocol (MCP) is built on a flexible, extensible architecture that enables seamless communication between LLM applications and integrations. This document covers the core architectural components and concepts.
 8605 | 
 8606 | ## Overview
 8607 | 
 8608 | MCP follows a client-server architecture where:
 8609 | 
 8610 | * **Hosts** are LLM applications (like Claude Desktop or IDEs) that initiate connections
 8611 | * **Clients** maintain 1:1 connections with servers, inside the host application
 8612 | * **Servers** provide context, tools, and prompts to clients
 8613 | 
 8614 | ```mermaid
 8615 | flowchart LR
 8616 |     subgraph "Host"
 8617 |         client1[MCP Client]
 8618 |         client2[MCP Client]
 8619 |     end
 8620 |     subgraph "Server Process"
 8621 |         server1[MCP Server]
 8622 |     end
 8623 |     subgraph "Server Process"
 8624 |         server2[MCP Server]
 8625 |     end
 8626 | 
 8627 |     client1 <-->|Transport Layer| server1
 8628 |     client2 <-->|Transport Layer| server2
 8629 | ```
 8630 | 
 8631 | ## Core components
 8632 | 
 8633 | ### Protocol layer
 8634 | 
 8635 | The protocol layer handles message framing, request/response linking, and high-level communication patterns.
 8636 | 
 8637 | <Tabs>
 8638 |   <Tab title="TypeScript">
 8639 |     ```typescript
 8640 |     class Protocol<Request, Notification, Result> {
 8641 |         // Handle incoming requests
 8642 |         setRequestHandler<T>(schema: T, handler: (request: T, extra: RequestHandlerExtra) => Promise<Result>): void
 8643 | 
 8644 |         // Handle incoming notifications
 8645 |         setNotificationHandler<T>(schema: T, handler: (notification: T) => Promise<void>): void
 8646 | 
 8647 |         // Send requests and await responses
 8648 |         request<T>(request: Request, schema: T, options?: RequestOptions): Promise<T>
 8649 | 
 8650 |         // Send one-way notifications
 8651 |         notification(notification: Notification): Promise<void>
 8652 |     }
 8653 |     ```
 8654 |   </Tab>
 8655 | 
 8656 |   <Tab title="Python">
 8657 |     ```python
 8658 |     class Session(BaseSession[RequestT, NotificationT, ResultT]):
 8659 |         async def send_request(
 8660 |             self,
 8661 |             request: RequestT,
 8662 |             result_type: type[Result]
 8663 |         ) -> Result:
 8664 |             """
 8665 |             Send request and wait for response. Raises McpError if response contains error.
 8666 |             """
 8667 |             # Request handling implementation
 8668 | 
 8669 |         async def send_notification(
 8670 |             self,
 8671 |             notification: NotificationT
 8672 |         ) -> None:
 8673 |             """Send one-way notification that doesn't expect response."""
 8674 |             # Notification handling implementation
 8675 | 
 8676 |         async def _received_request(
 8677 |             self,
 8678 |             responder: RequestResponder[ReceiveRequestT, ResultT]
 8679 |         ) -> None:
 8680 |             """Handle incoming request from other side."""
 8681 |             # Request handling implementation
 8682 | 
 8683 |         async def _received_notification(
 8684 |             self,
 8685 |             notification: ReceiveNotificationT
 8686 |         ) -> None:
 8687 |             """Handle incoming notification from other side."""
 8688 |             # Notification handling implementation
 8689 |     ```
 8690 |   </Tab>
 8691 | </Tabs>
 8692 | 
 8693 | Key classes include:
 8694 | 
 8695 | * `Protocol`
 8696 | * `Client`
 8697 | * `Server`
 8698 | 
 8699 | ### Transport layer
 8700 | 
 8701 | The transport layer handles the actual communication between clients and servers. MCP supports multiple transport mechanisms:
 8702 | 
 8703 | 1. **Stdio transport**
 8704 |    * Uses standard input/output for communication
 8705 |    * Ideal for local processes
 8706 | 
 8707 | 2. **HTTP with SSE transport**
 8708 |    * Uses Server-Sent Events for server-to-client messages
 8709 |    * HTTP POST for client-to-server messages
 8710 | 
 8711 | All transports use [JSON-RPC](https://www.jsonrpc.org/) 2.0 to exchange messages. See the [specification](https://spec.modelcontextprotocol.io) for detailed information about the Model Context Protocol message format.
 8712 | 
 8713 | ### Message types
 8714 | 
 8715 | MCP has these main types of messages:
 8716 | 
 8717 | 1. **Requests** expect a response from the other side:
 8718 |    ```typescript
 8719 |    interface Request {
 8720 |      method: string;
 8721 |      params?: { ... };
 8722 |    }
 8723 |    ```
 8724 | 
 8725 | 2. **Results** are successful responses to requests:
 8726 |    ```typescript
 8727 |    interface Result {
 8728 |      [key: string]: unknown;
 8729 |    }
 8730 |    ```
 8731 | 
 8732 | 3. **Errors** indicate that a request failed:
 8733 |    ```typescript
 8734 |    interface Error {
 8735 |      code: number;
 8736 |      message: string;
 8737 |      data?: unknown;
 8738 |    }
 8739 |    ```
 8740 | 
 8741 | 4. **Notifications** are one-way messages that don't expect a response:
 8742 |    ```typescript
 8743 |    interface Notification {
 8744 |      method: string;
 8745 |      params?: { ... };
 8746 |    }
 8747 |    ```
 8748 | 
 8749 | ## Connection lifecycle
 8750 | 
 8751 | ### 1. Initialization
 8752 | 
 8753 | ```mermaid
 8754 | sequenceDiagram
 8755 |     participant Client
 8756 |     participant Server
 8757 | 
 8758 |     Client->>Server: initialize request
 8759 |     Server->>Client: initialize response
 8760 |     Client->>Server: initialized notification
 8761 | 
 8762 |     Note over Client,Server: Connection ready for use
 8763 | ```
 8764 | 
 8765 | 1. Client sends `initialize` request with protocol version and capabilities
 8766 | 2. Server responds with its protocol version and capabilities
 8767 | 3. Client sends `initialized` notification as acknowledgment
 8768 | 4. Normal message exchange begins
 8769 | 
 8770 | ### 2. Message exchange
 8771 | 
 8772 | After initialization, the following patterns are supported:
 8773 | 
 8774 | * **Request-Response**: Client or server sends requests, the other responds
 8775 | * **Notifications**: Either party sends one-way messages
 8776 | 
 8777 | ### 3. Termination
 8778 | 
 8779 | Either party can terminate the connection:
 8780 | 
 8781 | * Clean shutdown via `close()`
 8782 | * Transport disconnection
 8783 | * Error conditions
 8784 | 
 8785 | ## Error handling
 8786 | 
 8787 | MCP defines these standard error codes:
 8788 | 
 8789 | ```typescript
 8790 | enum ErrorCode {
 8791 |   // Standard JSON-RPC error codes
 8792 |   ParseError = -32700,
 8793 |   InvalidRequest = -32600,
 8794 |   MethodNotFound = -32601,
 8795 |   InvalidParams = -32602,
 8796 |   InternalError = -32603
 8797 | }
 8798 | ```
 8799 | 
 8800 | SDKs and applications can define their own error codes above -32000.
 8801 | 
 8802 | Errors are propagated through:
 8803 | 
 8804 | * Error responses to requests
 8805 | * Error events on transports
 8806 | * Protocol-level error handlers
 8807 | 
 8808 | ## Implementation example
 8809 | 
 8810 | Here's a basic example of implementing an MCP server:
 8811 | 
 8812 | <Tabs>
 8813 |   <Tab title="TypeScript">
 8814 |     ```typescript
 8815 |     import { Server } from "@modelcontextprotocol/sdk/server/index.js";
 8816 |     import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
 8817 | 
 8818 |     const server = new Server({
 8819 |       name: "example-server",
 8820 |       version: "1.0.0"
 8821 |     }, {
 8822 |       capabilities: {
 8823 |         resources: {}
 8824 |       }
 8825 |     });
 8826 | 
 8827 |     // Handle requests
 8828 |     server.setRequestHandler(ListResourcesRequestSchema, async () => {
 8829 |       return {
 8830 |         resources: [
 8831 |           {
 8832 |             uri: "example://resource",
 8833 |             name: "Example Resource"
 8834 |           }
 8835 |         ]
 8836 |       };
 8837 |     });
 8838 | 
 8839 |     // Connect transport
 8840 |     const transport = new StdioServerTransport();
 8841 |     await server.connect(transport);
 8842 |     ```
 8843 |   </Tab>
 8844 | 
 8845 |   <Tab title="Python">
 8846 |     ```python
 8847 |     import asyncio
 8848 |     import mcp.types as types
 8849 |     from mcp.server import Server
 8850 |     from mcp.server.stdio import stdio_server
 8851 | 
 8852 |     app = Server("example-server")
 8853 | 
 8854 |     @app.list_resources()
 8855 |     async def list_resources() -> list[types.Resource]:
 8856 |         return [
 8857 |             types.Resource(
 8858 |                 uri="example://resource",
 8859 |                 name="Example Resource"
 8860 |             )
 8861 |         ]
 8862 | 
 8863 |     async def main():
 8864 |         async with stdio_server() as streams:
 8865 |             await app.run(
 8866 |                 streams[0],
 8867 |                 streams[1],
 8868 |                 app.create_initialization_options()
 8869 |             )
 8870 | 
 8871 |     if __name__ == "__main__":
 8872 |         asyncio.run(main)
 8873 |     ```
 8874 |   </Tab>
 8875 | </Tabs>
 8876 | 
 8877 | ## Best practices
 8878 | 
 8879 | ### Transport selection
 8880 | 
 8881 | 1. **Local communication**
 8882 |    * Use stdio transport for local processes
 8883 |    * Efficient for same-machine communication
 8884 |    * Simple process management
 8885 | 
 8886 | 2. **Remote communication**
 8887 |    * Use SSE for scenarios requiring HTTP compatibility
 8888 |    * Consider security implications including authentication and authorization
 8889 | 
 8890 | ### Message handling
 8891 | 
 8892 | 1. **Request processing**
 8893 |    * Validate inputs thoroughly
 8894 |    * Use type-safe schemas
 8895 |    * Handle errors gracefully
 8896 |    * Implement timeouts
 8897 | 
 8898 | 2. **Progress reporting**
 8899 |    * Use progress tokens for long operations
 8900 |    * Report progress incrementally
 8901 |    * Include total progress when known
 8902 | 
 8903 | 3. **Error management**
 8904 |    * Use appropriate error codes
 8905 |    * Include helpful error messages
 8906 |    * Clean up resources on errors
 8907 | 
 8908 | ## Security considerations
 8909 | 
 8910 | 1. **Transport security**
 8911 |    * Use TLS for remote connections
 8912 |    * Validate connection origins
 8913 |    * Implement authentication when needed
 8914 | 
 8915 | 2. **Message validation**
 8916 |    * Validate all incoming messages
 8917 |    * Sanitize inputs
 8918 |    * Check message size limits
 8919 |    * Verify JSON-RPC format
 8920 | 
 8921 | 3. **Resource protection**
 8922 |    * Implement access controls
 8923 |    * Validate resource paths
 8924 |    * Monitor resource usage
 8925 |    * Rate limit requests
 8926 | 
 8927 | 4. **Error handling**
 8928 |    * Don't leak sensitive information
 8929 |    * Log security-relevant errors
 8930 |    * Implement proper cleanup
 8931 |    * Handle DoS scenarios
 8932 | 
 8933 | ## Debugging and monitoring
 8934 | 
 8935 | 1. **Logging**
 8936 |    * Log protocol events
 8937 |    * Track message flow
 8938 |    * Monitor performance
 8939 |    * Record errors
 8940 | 
 8941 | 2. **Diagnostics**
 8942 |    * Implement health checks
 8943 |    * Monitor connection state
 8944 |    * Track resource usage
 8945 |    * Profile performance
 8946 | 
 8947 | 3. **Testing**
 8948 |    * Test different transports
 8949 |    * Verify error handling
 8950 |    * Check edge cases
 8951 |    * Load test servers
 8952 | 
 8953 | 
 8954 | # Prompts
 8955 | Source: https://modelcontextprotocol.io/docs/concepts/prompts
 8956 | 
 8957 | Create reusable prompt templates and workflows
 8958 | 
 8959 | Prompts enable servers to define reusable prompt templates and workflows that clients can easily surface to users and LLMs. They provide a powerful way to standardize and share common LLM interactions.
 8960 | 
 8961 | <Note>
 8962 |   Prompts are designed to be **user-controlled**, meaning they are exposed from servers to clients with the intention of the user being able to explicitly select them for use.
 8963 | </Note>
 8964 | 
 8965 | ## Overview
 8966 | 
 8967 | Prompts in MCP are predefined templates that can:
 8968 | 
 8969 | *   Accept dynamic arguments
 8970 | *   Include context from resources
 8971 | *   Chain multiple interactions
 8972 | *   Guide specific workflows
 8973 | *   Surface as UI elements (like slash commands)
 8974 | 
 8975 | ## Prompt structure
 8976 | 
 8977 | Each prompt is defined with:
 8978 | 
 8979 | ```typescript
 8980 | {
 8981 |   name: string;              // Unique identifier for the prompt
 8982 |   description?: string;      // Human-readable description
 8983 |   arguments?: [              // Optional list of arguments
 8984 |     {
 8985 |       name: string;          // Argument identifier
 8986 |       description?: string;  // Argument description
 8987 |       required?: boolean;    // Whether argument is required
 8988 |     }
 8989 |   ]
 8990 | }
 8991 | ```
 8992 | 
 8993 | ## Discovering prompts
 8994 | 
 8995 | Clients can discover available prompts through the `prompts/list` endpoint:
 8996 | 
 8997 | ```typescript
 8998 | // Request
 8999 | {
 9000 |   method: "prompts/list"
 9001 | }
 9002 | 
 9003 | // Response
 9004 | {
 9005 |   prompts: [
 9006 |     {
 9007 |       name: "analyze-code",
 9008 |       description: "Analyze code for potential improvements",
 9009 |       arguments: [
 9010 |         {
 9011 |           name: "language",
 9012 |           description: "Programming language",
 9013 |           required: true
 9014 |         }
 9015 |       ]
 9016 |     }
 9017 |   ]
 9018 | }
 9019 | ```
 9020 | 
 9021 | ## Using prompts
 9022 | 
 9023 | To use a prompt, clients make a `prompts/get` request:
 9024 | 
 9025 | ````typescript
 9026 | // Request
 9027 | {
 9028 |   method: "prompts/get",
 9029 |   params: {
 9030 |     name: "analyze-code",
 9031 |     arguments: {
 9032 |       language: "python"
 9033 |     }
 9034 |   }
 9035 | }
 9036 | 
 9037 | // Response
 9038 | {
 9039 |   description: "Analyze Python code for potential improvements",
 9040 |   messages: [
 9041 |     {
 9042 |       role: "user",
 9043 |       content: {
 9044 |         type: "text",
 9045 |         text: "Please analyze the following Python code for potential improvements:\n\n```python\ndef calculate_sum(numbers):\n    total = 0\n    for num in numbers:\n        total = total + num\n    return total\n\nresult = calculate_sum([1, 2, 3, 4, 5])\nprint(result)\n```"
 9046 |       }
 9047 |     }
 9048 |   ]
 9049 | }
 9050 | ````
 9051 | 
 9052 | ## Dynamic prompts
 9053 | 
 9054 | Prompts can be dynamic and include:
 9055 | 
 9056 | ### Embedded resource context
 9057 | 
 9058 | ```json
 9059 | {
 9060 |   "name": "analyze-project",
 9061 |   "description": "Analyze project logs and code",
 9062 |   "arguments": [
 9063 |     {
 9064 |       "name": "timeframe",
 9065 |       "description": "Time period to analyze logs",
 9066 |       "required": true
 9067 |     },
 9068 |     {
 9069 |       "name": "fileUri",
 9070 |       "description": "URI of code file to review",
 9071 |       "required": true
 9072 |     }
 9073 |   ]
 9074 | }
 9075 | ```
 9076 | 
 9077 | When handling the `prompts/get` request:
 9078 | 
 9079 | ```json
 9080 | {
 9081 |   "messages": [
 9082 |     {
 9083 |       "role": "user",
 9084 |       "content": {
 9085 |         "type": "text",
 9086 |         "text": "Analyze these system logs and the code file for any issues:"
 9087 |       }
 9088 |     },
 9089 |     {
 9090 |       "role": "user",
 9091 |       "content": {
 9092 |         "type": "resource",
 9093 |         "resource": {
 9094 |           "uri": "logs://recent?timeframe=1h",
 9095 |           "text": "[2024-03-14 15:32:11] ERROR: Connection timeout in network.py:127\n[2024-03-14 15:32:15] WARN: Retrying connection (attempt 2/3)\n[2024-03-14 15:32:20] ERROR: Max retries exceeded",
 9096 |           "mimeType": "text/plain"
 9097 |         }
 9098 |       }
 9099 |     },
 9100 |     {
 9101 |       "role": "user",
 9102 |       "content": {
 9103 |         "type": "resource",
 9104 |         "resource": {
 9105 |           "uri": "file:///path/to/code.py",
 9106 |           "text": "def connect_to_service(timeout=30):\n    retries = 3\n    for attempt in range(retries):\n        try:\n            return establish_connection(timeout)\n        except TimeoutError:\n            if attempt == retries - 1:\n                raise\n            time.sleep(5)\n\ndef establish_connection(timeout):\n    # Connection implementation\n    pass",
 9107 |           "mimeType": "text/x-python"
 9108 |         }
 9109 |       }
 9110 |     }
 9111 |   ]
 9112 | }
 9113 | ```
 9114 | 
 9115 | ### Multi-step workflows
 9116 | 
 9117 | ```typescript
 9118 | const debugWorkflow = {
 9119 |   name: "debug-error",
 9120 |   async getMessages(error: string) {
 9121 |     return [
 9122 |       {
 9123 |         role: "user",
 9124 |         content: {
 9125 |           type: "text",
 9126 |           text: `Here's an error I'm seeing: ${error}`
 9127 |         }
 9128 |       },
 9129 |       {
 9130 |         role: "assistant",
 9131 |         content: {
 9132 |           type: "text",
 9133 |           text: "I'll help analyze this error. What have you tried so far?"
 9134 |         }
 9135 |       },
 9136 |       {
 9137 |         role: "user",
 9138 |         content: {
 9139 |           type: "text",
 9140 |           text: "I've tried restarting the service, but the error persists."
 9141 |         }
 9142 |       }
 9143 |     ];
 9144 |   }
 9145 | };
 9146 | ```
 9147 | 
 9148 | ## Example implementation
 9149 | 
 9150 | Here's a complete example of implementing prompts in an MCP server:
 9151 | 
 9152 | <Tabs>
 9153 |   <Tab title="TypeScript">
 9154 |     ```typescript
 9155 |     import { Server } from "@modelcontextprotocol/sdk/server";
 9156 |     import {
 9157 |       ListPromptsRequestSchema,
 9158 |       GetPromptRequestSchema
 9159 |     } from "@modelcontextprotocol/sdk/types";
 9160 | 
 9161 |     const PROMPTS = {
 9162 |       "git-commit": {
 9163 |         name: "git-commit",
 9164 |         description: "Generate a Git commit message",
 9165 |         arguments: [
 9166 |           {
 9167 |             name: "changes",
 9168 |             description: "Git diff or description of changes",
 9169 |             required: true
 9170 |           }
 9171 |         ]
 9172 |       },
 9173 |       "explain-code": {
 9174 |         name: "explain-code",
 9175 |         description: "Explain how code works",
 9176 |         arguments: [
 9177 |           {
 9178 |             name: "code",
 9179 |             description: "Code to explain",
 9180 |             required: true
 9181 |           },
 9182 |           {
 9183 |             name: "language",
 9184 |             description: "Programming language",
 9185 |             required: false
 9186 |           }
 9187 |         ]
 9188 |       }
 9189 |     };
 9190 | 
 9191 |     const server = new Server({
 9192 |       name: "example-prompts-server",
 9193 |       version: "1.0.0"
 9194 |     }, {
 9195 |       capabilities: {
 9196 |         prompts: {}
 9197 |       }
 9198 |     });
 9199 | 
 9200 |     // List available prompts
 9201 |     server.setRequestHandler(ListPromptsRequestSchema, async () => {
 9202 |       return {
 9203 |         prompts: Object.values(PROMPTS)
 9204 |       };
 9205 |     });
 9206 | 
 9207 |     // Get specific prompt
 9208 |     server.setRequestHandler(GetPromptRequestSchema, async (request) => {
 9209 |       const prompt = PROMPTS[request.params.name];
 9210 |       if (!prompt) {
 9211 |         throw new Error(`Prompt not found: ${request.params.name}`);
 9212 |       }
 9213 | 
 9214 |       if (request.params.name === "git-commit") {
 9215 |         return {
 9216 |           messages: [
 9217 |             {
 9218 |               role: "user",
 9219 |               content: {
 9220 |                 type: "text",
 9221 |                 text: `Generate a concise but descriptive commit message for these changes:\n\n${request.params.arguments?.changes}`
 9222 |               }
 9223 |             }
 9224 |           ]
 9225 |         };
 9226 |       }
 9227 | 
 9228 |       if (request.params.name === "explain-code") {
 9229 |         const language = request.params.arguments?.language || "Unknown";
 9230 |         return {
 9231 |           messages: [
 9232 |             {
 9233 |               role: "user",
 9234 |               content: {
 9235 |                 type: "text",
 9236 |                 text: `Explain how this ${language} code works:\n\n${request.params.arguments?.code}`
 9237 |               }
 9238 |             }
 9239 |           ]
 9240 |         };
 9241 |       }
 9242 | 
 9243 |       throw new Error("Prompt implementation not found");
 9244 |     });
 9245 |     ```
 9246 |   </Tab>
 9247 | 
 9248 |   <Tab title="Python">
 9249 |     ```python
 9250 |     from mcp.server import Server
 9251 |     import mcp.types as types
 9252 | 
 9253 |     # Define available prompts
 9254 |     PROMPTS = {
 9255 |         "git-commit": types.Prompt(
 9256 |             name="git-commit",
 9257 |             description="Generate a Git commit message",
 9258 |             arguments=[
 9259 |                 types.PromptArgument(
 9260 |                     name="changes",
 9261 |                     description="Git diff or description of changes",
 9262 |                     required=True
 9263 |                 )
 9264 |             ],
 9265 |         ),
 9266 |         "explain-code": types.Prompt(
 9267 |             name="explain-code",
 9268 |             description="Explain how code works",
 9269 |             arguments=[
 9270 |                 types.PromptArgument(
 9271 |                     name="code",
 9272 |                     description="Code to explain",
 9273 |                     required=True
 9274 |                 ),
 9275 |                 types.PromptArgument(
 9276 |                     name="language",
 9277 |                     description="Programming language",
 9278 |                     required=False
 9279 |                 )
 9280 |             ],
 9281 |         )
 9282 |     }
 9283 | 
 9284 |     # Initialize server
 9285 |     app = Server("example-prompts-server")
 9286 | 
 9287 |     @app.list_prompts()
 9288 |     async def list_prompts() -> list[types.Prompt]:
 9289 |         return list(PROMPTS.values())
 9290 | 
 9291 |     @app.get_prompt()
 9292 |     async def get_prompt(
 9293 |         name: str, arguments: dict[str, str] | None = None
 9294 |     ) -> types.GetPromptResult:
 9295 |         if name not in PROMPTS:
 9296 |             raise ValueError(f"Prompt not found: {name}")
 9297 | 
 9298 |         if name == "git-commit":
 9299 |             changes = arguments.get("changes") if arguments else ""
 9300 |             return types.GetPromptResult(
 9301 |                 messages=[
 9302 |                     types.PromptMessage(
 9303 |                         role="user",
 9304 |                         content=types.TextContent(
 9305 |                             type="text",
 9306 |                             text=f"Generate a concise but descriptive commit message "
 9307 |                             f"for these changes:\n\n{changes}"
 9308 |                         )
 9309 |                     )
 9310 |                 ]
 9311 |             )
 9312 | 
 9313 |         if name == "explain-code":
 9314 |             code = arguments.get("code") if arguments else ""
 9315 |             language = arguments.get("language", "Unknown") if arguments else "Unknown"
 9316 |             return types.GetPromptResult(
 9317 |                 messages=[
 9318 |                     types.PromptMessage(
 9319 |                         role="user",
 9320 |                         content=types.TextContent(
 9321 |                             type="text",
 9322 |                             text=f"Explain how this {language} code works:\n\n{code}"
 9323 |                         )
 9324 |                     )
 9325 |                 ]
 9326 |             )
 9327 | 
 9328 |         raise ValueError("Prompt implementation not found")
 9329 |     ```
 9330 |   </Tab>
 9331 | </Tabs>
 9332 | 
 9333 | ## Best practices
 9334 | 
 9335 | When implementing prompts:
 9336 | 
 9337 | 1.  Use clear, descriptive prompt names
 9338 | 2.  Provide detailed descriptions for prompts and arguments
 9339 | 3.  Validate all required arguments
 9340 | 4.  Handle missing arguments gracefully
 9341 | 5.  Consider versioning for prompt templates
 9342 | 6.  Cache dynamic content when appropriate
 9343 | 7.  Implement error handling
 9344 | 8.  Document expected argument formats
 9345 | 9.  Consider prompt composability
 9346 | 10. Test prompts with various inputs
 9347 | 
 9348 | ## UI integration
 9349 | 
 9350 | Prompts can be surfaced in client UIs as:
 9351 | 
 9352 | *   Slash commands
 9353 | *   Quick actions
 9354 | *   Context menu items
 9355 | *   Command palette entries
 9356 | *   Guided workflows
 9357 | *   Interactive forms
 9358 | 
 9359 | ## Updates and changes
 9360 | 
 9361 | Servers can notify clients about prompt changes:
 9362 | 
 9363 | 1.  Server capability: `prompts.listChanged`
 9364 | 2.  Notification: `notifications/prompts/list_changed`
 9365 | 3.  Client re-fetches prompt list
 9366 | 
 9367 | ## Security considerations
 9368 | 
 9369 | When implementing prompts:
 9370 | 
 9371 | *   Validate all arguments
 9372 | *   Sanitize user input
 9373 | *   Consider rate limiting
 9374 | *   Implement access controls
 9375 | *   Audit prompt usage
 9376 | *   Handle sensitive data appropriately
 9377 | *   Validate generated content
 9378 | *   Implement timeouts
 9379 | *   Consider prompt injection risks
 9380 | *   Document security requirements
 9381 | 
 9382 | 
 9383 | # Resources
 9384 | Source: https://modelcontextprotocol.io/docs/concepts/resources
 9385 | 
 9386 | Expose data and content from your servers to LLMs
 9387 | 
 9388 | Resources are a core primitive in the Model Context Protocol (MCP) that allow servers to expose data and content that can be read by clients and used as context for LLM interactions.
 9389 | 
 9390 | <Note>
 9391 |   Resources are designed to be **application-controlled**, meaning that the client application can decide how and when they should be used.
 9392 |   Different MCP clients may handle resources differently. For example:
 9393 | 
 9394 |   *   Claude Desktop currently requires users to explicitly select resources before they can be used
 9395 |   *   Other clients might automatically select resources based on heuristics
 9396 |   *   Some implementations may even allow the AI model itself to determine which resources to use
 9397 | 
 9398 |   Server authors should be prepared to handle any of these interaction patterns when implementing resource support. In order to expose data to models automatically, server authors should use a **model-controlled** primitive such as [Tools](./tools).
 9399 | </Note>
 9400 | 
 9401 | ## Overview
 9402 | 
 9403 | Resources represent any kind of data that an MCP server wants to make available to clients. This can include:
 9404 | 
 9405 | *   File contents
 9406 | *   Database records
 9407 | *   API responses
 9408 | *   Live system data
 9409 | *   Screenshots and images
 9410 | *   Log files
 9411 | *   And more
 9412 | 
 9413 | Each resource is identified by a unique URI and can contain either text or binary data.
 9414 | 
 9415 | ## Resource URIs
 9416 | 
 9417 | Resources are identified using URIs that follow this format:
 9418 | 
 9419 | ```
 9420 | [protocol]://[host]/[path]
 9421 | ```
 9422 | 
 9423 | For example:
 9424 | 
 9425 | *   `file:///home/user/documents/report.pdf`
 9426 | *   `postgres://database/customers/schema`
 9427 | *   `screen://localhost/display1`
 9428 | 
 9429 | The protocol and path structure is defined by the MCP server implementation. Servers can define their own custom URI schemes.
 9430 | 
 9431 | ## Resource types
 9432 | 
 9433 | Resources can contain two types of content:
 9434 | 
 9435 | ### Text resources
 9436 | 
 9437 | Text resources contain UTF-8 encoded text data. These are suitable for:
 9438 | 
 9439 | *   Source code
 9440 | *   Configuration files
 9441 | *   Log files
 9442 | *   JSON/XML data
 9443 | *   Plain text
 9444 | 
 9445 | ### Binary resources
 9446 | 
 9447 | Binary resources contain raw binary data encoded in base64. These are suitable for:
 9448 | 
 9449 | *   Images
 9450 | *   PDFs
 9451 | *   Audio files
 9452 | *   Video files
 9453 | *   Other non-text formats
 9454 | 
 9455 | ## Resource discovery
 9456 | 
 9457 | Clients can discover available resources through two main methods:
 9458 | 
 9459 | ### Direct resources
 9460 | 
 9461 | Servers expose a list of concrete resources via the `resources/list` endpoint. Each resource includes:
 9462 | 
 9463 | ```typescript
 9464 | {
 9465 |   uri: string;           // Unique identifier for the resource
 9466 |   name: string;          // Human-readable name
 9467 |   description?: string;  // Optional description
 9468 |   mimeType?: string;     // Optional MIME type
 9469 | }
 9470 | ```
 9471 | 
 9472 | ### Resource templates
 9473 | 
 9474 | For dynamic resources, servers can expose [URI templates](https://datatracker.ietf.org/doc/html/rfc6570) that clients can use to construct valid resource URIs:
 9475 | 
 9476 | ```typescript
 9477 | {
 9478 |   uriTemplate: string;   // URI template following RFC 6570
 9479 |   name: string;          // Human-readable name for this type
 9480 |   description?: string;  // Optional description
 9481 |   mimeType?: string;     // Optional MIME type for all matching resources
 9482 | }
 9483 | ```
 9484 | 
 9485 | ## Reading resources
 9486 | 
 9487 | To read a resource, clients make a `resources/read` request with the resource URI.
 9488 | 
 9489 | The server responds with a list of resource contents:
 9490 | 
 9491 | ```typescript
 9492 | {
 9493 |   contents: [
 9494 |     {
 9495 |       uri: string;        // The URI of the resource
 9496 |       mimeType?: string;  // Optional MIME type
 9497 | 
 9498 |       // One of:
 9499 |       text?: string;      // For text resources
 9500 |       blob?: string;      // For binary resources (base64 encoded)
 9501 |     }
 9502 |   ]
 9503 | }
 9504 | ```
 9505 | 
 9506 | <Tip>
 9507 |   Servers may return multiple resources in response to one `resources/read` request. This could be used, for example, to return a list of files inside a directory when the directory is read.
 9508 | </Tip>
 9509 | 
 9510 | ## Resource updates
 9511 | 
 9512 | MCP supports real-time updates for resources through two mechanisms:
 9513 | 
 9514 | ### List changes
 9515 | 
 9516 | Servers can notify clients when their list of available resources changes via the `notifications/resources/list_changed` notification.
 9517 | 
 9518 | ### Content changes
 9519 | 
 9520 | Clients can subscribe to updates for specific resources:
 9521 | 
 9522 | 1.  Client sends `resources/subscribe` with resource URI
 9523 | 2.  Server sends `notifications/resources/updated` when the resource changes
 9524 | 3.  Client can fetch latest content with `resources/read`
 9525 | 4.  Client can unsubscribe with `resources/unsubscribe`
 9526 | 
 9527 | ## Example implementation
 9528 | 
 9529 | Here's a simple example of implementing resource support in an MCP server:
 9530 | 
 9531 | <Tabs>
 9532 |   <Tab title="TypeScript">
 9533 |     ```typescript
 9534 |     const server = new Server({
 9535 |       name: "example-server",
 9536 |       version: "1.0.0"
 9537 |     }, {
 9538 |       capabilities: {
 9539 |         resources: {}
 9540 |       }
 9541 |     });
 9542 | 
 9543 |     // List available resources
 9544 |     server.setRequestHandler(ListResourcesRequestSchema, async () => {
 9545 |       return {
 9546 |         resources: [
 9547 |           {
 9548 |             uri: "file:///logs/app.log",
 9549 |             name: "Application Logs",
 9550 |             mimeType: "text/plain"
 9551 |           }
 9552 |         ]
 9553 |       };
 9554 |     });
 9555 | 
 9556 |     // Read resource contents
 9557 |     server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
 9558 |       const uri = request.params.uri;
 9559 | 
 9560 |       if (uri === "file:///logs/app.log") {
 9561 |         const logContents = await readLogFile();
 9562 |         return {
 9563 |           contents: [
 9564 |             {
 9565 |               uri,
 9566 |               mimeType: "text/plain",
 9567 |               text: logContents
 9568 |             }
 9569 |           ]
 9570 |         };
 9571 |       }
 9572 | 
 9573 |       throw new Error("Resource not found");
 9574 |     });
 9575 |     ```
 9576 |   </Tab>
 9577 | 
 9578 |   <Tab title="Python">
 9579 |     ```python
 9580 |     app = Server("example-server")
 9581 | 
 9582 |     @app.list_resources()
 9583 |     async def list_resources() -> list[types.Resource]:
 9584 |         return [
 9585 |             types.Resource(
 9586 |                 uri="file:///logs/app.log",
 9587 |                 name="Application Logs",
 9588 |                 mimeType="text/plain"
 9589 |             )
 9590 |         ]
 9591 | 
 9592 |     @app.read_resource()
 9593 |     async def read_resource(uri: AnyUrl) -> str:
 9594 |         if str(uri) == "file:///logs/app.log":
 9595 |             log_contents = await read_log_file()
 9596 |             return log_contents
 9597 | 
 9598 |         raise ValueError("Resource not found")
 9599 | 
 9600 |     # Start server
 9601 |     async with stdio_server() as streams:
 9602 |         await app.run(
 9603 |             streams[0],
 9604 |             streams[1],
 9605 |             app.create_initialization_options()
 9606 |         )
 9607 |     ```
 9608 |   </Tab>
 9609 | </Tabs>
 9610 | 
 9611 | ## Best practices
 9612 | 
 9613 | When implementing resource support:
 9614 | 
 9615 | 1.  Use clear, descriptive resource names and URIs
 9616 | 2.  Include helpful descriptions to guide LLM understanding
 9617 | 3.  Set appropriate MIME types when known
 9618 | 4.  Implement resource templates for dynamic content
 9619 | 5.  Use subscriptions for frequently changing resources
 9620 | 6.  Handle errors gracefully with clear error messages
 9621 | 7.  Consider pagination for large resource lists
 9622 | 8.  Cache resource contents when appropriate
 9623 | 9.  Validate URIs before processing
 9624 | 10. Document your custom URI schemes
 9625 | 
 9626 | ## Security considerations
 9627 | 
 9628 | When exposing resources:
 9629 | 
 9630 | *   Validate all resource URIs
 9631 | *   Implement appropriate access controls
 9632 | *   Sanitize file paths to prevent directory traversal
 9633 | *   Be cautious with binary data handling
 9634 | *   Consider rate limiting for resource reads
 9635 | *   Audit resource access
 9636 | *   Encrypt sensitive data in transit
 9637 | *   Validate MIME types
 9638 | *   Implement timeouts for long-running reads
 9639 | *   Handle resource cleanup appropriately
 9640 | 
 9641 | 
 9642 | # Roots
 9643 | Source: https://modelcontextprotocol.io/docs/concepts/roots
 9644 | 
 9645 | Understanding roots in MCP
 9646 | 
 9647 | Roots are a concept in MCP that define the boundaries where servers can operate. They provide a way for clients to inform servers about relevant resources and their locations.
 9648 | 
 9649 | ## What are Roots?
 9650 | 
 9651 | A root is a URI that a client suggests a server should focus on. When a client connects to a server, it declares which roots the server should work with. While primarily used for filesystem paths, roots can be any valid URI including HTTP URLs.
 9652 | 
 9653 | For example, roots could be:
 9654 | 
 9655 | ```
 9656 | file:///home/user/projects/myapp
 9657 | https://api.example.com/v1
 9658 | ```
 9659 | 
 9660 | ## Why Use Roots?
 9661 | 
 9662 | Roots serve several important purposes:
 9663 | 
 9664 | 1.  **Guidance**: They inform servers about relevant resources and locations
 9665 | 2.  **Clarity**: Roots make it clear which resources are part of your workspace
 9666 | 3.  **Organization**: Multiple roots let you work with different resources simultaneously
 9667 | 
 9668 | ## How Roots Work
 9669 | 
 9670 | When a client supports roots, it:
 9671 | 
 9672 | 1.  Declares the `roots` capability during connection
 9673 | 2.  Provides a list of suggested roots to the server
 9674 | 3.  Notifies the server when roots change (if supported)
 9675 | 
 9676 | While roots are informational and not strictly enforcing, servers should:
 9677 | 
 9678 | 1.  Respect the provided roots
 9679 | 2.  Use root URIs to locate and access resources
 9680 | 3.  Prioritize operations within root boundaries
 9681 | 
 9682 | ## Common Use Cases
 9683 | 
 9684 | Roots are commonly used to define:
 9685 | 
 9686 | *   Project directories
 9687 | *   Repository locations
 9688 | *   API endpoints
 9689 | *   Configuration locations
 9690 | *   Resource boundaries
 9691 | 
 9692 | ## Best Practices
 9693 | 
 9694 | When working with roots:
 9695 | 
 9696 | 1.  Only suggest necessary resources
 9697 | 2.  Use clear, descriptive names for roots
 9698 | 3.  Monitor root accessibility
 9699 | 4.  Handle root changes gracefully
 9700 | 
 9701 | ## Example
 9702 | 
 9703 | Here's how a typical MCP client might expose roots:
 9704 | 
 9705 | ```json
 9706 | {
 9707 |   "roots": [
 9708 |     {
 9709 |       "uri": "file:///home/user/projects/frontend",
 9710 |       "name": "Frontend Repository"
 9711 |     },
 9712 |     {
 9713 |       "uri": "https://api.example.com/v1",
 9714 |       "name": "API Endpoint"
 9715 |     }
 9716 |   ]
 9717 | }
 9718 | ```
 9719 | 
 9720 | This configuration suggests the server focus on both a local repository and an API endpoint while keeping them logically separated.
 9721 | 
 9722 | 
 9723 | # Sampling
 9724 | Source: https://modelcontextprotocol.io/docs/concepts/sampling
 9725 | 
 9726 | Let your servers request completions from LLMs
 9727 | 
 9728 | Sampling is a powerful MCP feature that allows servers to request LLM completions through the client, enabling sophisticated agentic behaviors while maintaining security and privacy.
 9729 | 
 9730 | <Info>
 9731 |   This feature of MCP is not yet supported in the Claude Desktop client.
 9732 | </Info>
 9733 | 
 9734 | ## How sampling works
 9735 | 
 9736 | The sampling flow follows these steps:
 9737 | 
 9738 | 1.  Server sends a `sampling/createMessage` request to the client
 9739 | 2.  Client reviews the request and can modify it
 9740 | 3.  Client samples from an LLM
 9741 | 4.  Client reviews the completion
 9742 | 5.  Client returns the result to the server
 9743 | 
 9744 | This human-in-the-loop design ensures users maintain control over what the LLM sees and generates.
 9745 | 
 9746 | ## Message format
 9747 | 
 9748 | Sampling requests use a standardized message format:
 9749 | 
 9750 | ```typescript
 9751 | {
 9752 |   messages: [
 9753 |     {
 9754 |       role: "user" | "assistant",
 9755 |       content: {
 9756 |         type: "text" | "image",
 9757 | 
 9758 |         // For text:
 9759 |         text?: string,
 9760 | 
 9761 |         // For images:
 9762 |         data?: string,             // base64 encoded
 9763 |         mimeType?: string
 9764 |       }
 9765 |     }
 9766 |   ],
 9767 |   modelPreferences?: {
 9768 |     hints?: [{
 9769 |       name?: string                // Suggested model name/family
 9770 |     }],
 9771 |     costPriority?: number,         // 0-1, importance of minimizing cost
 9772 |     speedPriority?: number,        // 0-1, importance of low latency
 9773 |     intelligencePriority?: number  // 0-1, importance of capabilities
 9774 |   },
 9775 |   systemPrompt?: string,
 9776 |   includeContext?: "none" | "thisServer" | "allServers",
 9777 |   temperature?: number,
 9778 |   maxTokens: number,
 9779 |   stopSequences?: string[],
 9780 |   metadata?: Record<string, unknown>
 9781 | }
 9782 | ```
 9783 | 
 9784 | ## Request parameters
 9785 | 
 9786 | ### Messages
 9787 | 
 9788 | The `messages` array contains the conversation history to send to the LLM. Each message has:
 9789 | 
 9790 | *   `role`: Either "user" or "assistant"
 9791 | *   `content`: The message content, which can be:
 9792 |     *   Text content with a `text` field
 9793 |     *   Image content with `data` (base64) and `mimeType` fields
 9794 | 
 9795 | ### Model preferences
 9796 | 
 9797 | The `modelPreferences` object allows servers to specify their model selection preferences:
 9798 | 
 9799 | *   `hints`: Array of model name suggestions that clients can use to select an appropriate model:
 9800 |     *   `name`: String that can match full or partial model names (e.g. "claude-3", "sonnet")
 9801 |     *   Clients may map hints to equivalent models from different providers
 9802 |     *   Multiple hints are evaluated in preference order
 9803 | 
 9804 | *   Priority values (0-1 normalized):
 9805 |     *   `costPriority`: Importance of minimizing costs
 9806 |     *   `speedPriority`: Importance of low latency response
 9807 |     *   `intelligencePriority`: Importance of advanced model capabilities
 9808 | 
 9809 | Clients make the final model selection based on these preferences and their available models.
 9810 | 
 9811 | ### System prompt
 9812 | 
 9813 | An optional `systemPrompt` field allows servers to request a specific system prompt. The client may modify or ignore this.
 9814 | 
 9815 | ### Context inclusion
 9816 | 
 9817 | The `includeContext` parameter specifies what MCP context to include:
 9818 | 
 9819 | *   `"none"`: No additional context
 9820 | *   `"thisServer"`: Include context from the requesting server
 9821 | *   `"allServers"`: Include context from all connected MCP servers
 9822 | 
 9823 | The client controls what context is actually included.
 9824 | 
 9825 | ### Sampling parameters
 9826 | 
 9827 | Fine-tune the LLM sampling with:
 9828 | 
 9829 | *   `temperature`: Controls randomness (0.0 to 1.0)
 9830 | *   `maxTokens`: Maximum tokens to generate
 9831 | *   `stopSequences`: Array of sequences that stop generation
 9832 | *   `metadata`: Additional provider-specific parameters
 9833 | 
 9834 | ## Response format
 9835 | 
 9836 | The client returns a completion result:
 9837 | 
 9838 | ```typescript
 9839 | {
 9840 |   model: string,  // Name of the model used
 9841 |   stopReason?: "endTurn" | "stopSequence" | "maxTokens" | string,
 9842 |   role: "user" | "assistant",
 9843 |   content: {
 9844 |     type: "text" | "image",
 9845 |     text?: string,
 9846 |     data?: string,
 9847 |     mimeType?: string
 9848 |   }
 9849 | }
 9850 | ```
 9851 | 
 9852 | ## Example request
 9853 | 
 9854 | Here's an example of requesting sampling from a client:
 9855 | 
 9856 | ```json
 9857 | {
 9858 |   "method": "sampling/createMessage",
 9859 |   "params": {
 9860 |     "messages": [
 9861 |       {
 9862 |         "role": "user",
 9863 |         "content": {
 9864 |           "type": "text",
 9865 |           "text": "What files are in the current directory?"
 9866 |         }
 9867 |       }
 9868 |     ],
 9869 |     "systemPrompt": "You are a helpful file system assistant.",
 9870 |     "includeContext": "thisServer",
 9871 |     "maxTokens": 100
 9872 |   }
 9873 | }
 9874 | ```
 9875 | 
 9876 | ## Best practices
 9877 | 
 9878 | When implementing sampling:
 9879 | 
 9880 | 1.  Always provide clear, well-structured prompts
 9881 | 2.  Handle both text and image content appropriately
 9882 | 3.  Set reasonable token limits
 9883 | 4.  Include relevant context through `includeContext`
 9884 | 5.  Validate responses before using them
 9885 | 6.  Handle errors gracefully
 9886 | 7.  Consider rate limiting sampling requests
 9887 | 8.  Document expected sampling behavior
 9888 | 9.  Test with various model parameters
 9889 | 10. Monitor sampling costs
 9890 | 
 9891 | ## Human in the loop controls
 9892 | 
 9893 | Sampling is designed with human oversight in mind:
 9894 | 
 9895 | ### For prompts
 9896 | 
 9897 | *   Clients should show users the proposed prompt
 9898 | *   Users should be able to modify or reject prompts
 9899 | *   System prompts can be filtered or modified
 9900 | *   Context inclusion is controlled by the client
 9901 | 
 9902 | ### For completions
 9903 | 
 9904 | *   Clients should show users the completion
 9905 | *   Users should be able to modify or reject completions
 9906 | *   Clients can filter or modify completions
 9907 | *   Users control which model is used
 9908 | 
 9909 | ## Security considerations
 9910 | 
 9911 | When implementing sampling:
 9912 | 
 9913 | *   Validate all message content
 9914 | *   Sanitize sensitive information
 9915 | *   Implement appropriate rate limits
 9916 | *   Monitor sampling usage
 9917 | *   Encrypt data in transit
 9918 | *   Handle user data privacy
 9919 | *   Audit sampling requests
 9920 | *   Control cost exposure
 9921 | *   Implement timeouts
 9922 | *   Handle model errors gracefully
 9923 | 
 9924 | ## Common patterns
 9925 | 
 9926 | ### Agentic workflows
 9927 | 
 9928 | Sampling enables agentic patterns like:
 9929 | 
 9930 | *   Reading and analyzing resources
 9931 | *   Making decisions based on context
 9932 | *   Generating structured data
 9933 | *   Handling multi-step tasks
 9934 | *   Providing interactive assistance
 9935 | 
 9936 | ### Context management
 9937 | 
 9938 | Best practices for context:
 9939 | 
 9940 | *   Request minimal necessary context
 9941 | *   Structure context clearly
 9942 | *   Handle context size limits
 9943 | *   Update context as needed
 9944 | *   Clean up stale context
 9945 | 
 9946 | ### Error handling
 9947 | 
 9948 | Robust error handling should:
 9949 | 
 9950 | *   Catch sampling failures
 9951 | *   Handle timeout errors
 9952 | *   Manage rate limits
 9953 | *   Validate responses
 9954 | *   Provide fallback behaviors
 9955 | *   Log errors appropriately
 9956 | 
 9957 | ## Limitations
 9958 | 
 9959 | Be aware of these limitations:
 9960 | 
 9961 | *   Sampling depends on client capabilities
 9962 | *   Users control sampling behavior
 9963 | *   Context size has limits
 9964 | *   Rate limits may apply
 9965 | *   Costs should be considered
 9966 | *   Model availability varies
 9967 | *   Response times vary
 9968 | *   Not all content types supported
 9969 | 
 9970 | 
 9971 | # Tools
 9972 | Source: https://modelcontextprotocol.io/docs/concepts/tools
 9973 | 
 9974 | Enable LLMs to perform actions through your server
 9975 | 
 9976 | Tools are a powerful primitive in the Model Context Protocol (MCP) that enable servers to expose executable functionality to clients. Through tools, LLMs can interact with external systems, perform computations, and take actions in the real world.
 9977 | 
 9978 | <Note>
 9979 |   Tools are designed to be **model-controlled**, meaning that tools are exposed from servers to clients with the intention of the AI model being able to automatically invoke them (with a human in the loop to grant approval).
 9980 | </Note>
 9981 | 
 9982 | ## Overview
 9983 | 
 9984 | Tools in MCP allow servers to expose executable functions that can be invoked by clients and used by LLMs to perform actions. Key aspects of tools include:
 9985 | 
 9986 | *   **Discovery**: Clients can list available tools through the `tools/list` endpoint
 9987 | *   **Invocation**: Tools are called using the `tools/call` endpoint, where servers perform the requested operation and return results
 9988 | *   **Flexibility**: Tools can range from simple calculations to complex API interactions
 9989 | 
 9990 | Like [resources](/docs/concepts/resources), tools are identified by unique names and can include descriptions to guide their usage. However, unlike resources, tools represent dynamic operations that can modify state or interact with external systems.
 9991 | 
 9992 | ## Tool definition structure
 9993 | 
 9994 | Each tool is defined with the following structure:
 9995 | 
 9996 | ```typescript
 9997 | {
 9998 |   name: string;          // Unique identifier for the tool
 9999 |   description?: string;  // Human-readable description
10000 |   inputSchema: {         // JSON Schema for the tool's parameters
10001 |     type: "object",
10002 |     properties: { ... }  // Tool-specific parameters
10003 |   }
10004 | }
10005 | ```
10006 | 
10007 | ## Implementing tools
10008 | 
10009 | Here's an example of implementing a basic tool in an MCP server:
10010 | 
10011 | <Tabs>
10012 |   <Tab title="TypeScript">
10013 |     ```typescript
10014 |     const server = new Server({
10015 |       name: "example-server",
10016 |       version: "1.0.0"
10017 |     }, {
10018 |       capabilities: {
10019 |         tools: {}
10020 |       }
10021 |     });
10022 | 
10023 |     // Define available tools
10024 |     server.setRequestHandler(ListToolsRequestSchema, async () => {
10025 |       return {
10026 |         tools: [{
10027 |           name: "calculate_sum",
10028 |           description: "Add two numbers together",
10029 |           inputSchema: {
10030 |             type: "object",
10031 |             properties: {
10032 |               a: { type: "number" },
10033 |               b: { type: "number" }
10034 |             },
10035 |             required: ["a", "b"]
10036 |           }
10037 |         }]
10038 |       };
10039 |     });
10040 | 
10041 |     // Handle tool execution
10042 |     server.setRequestHandler(CallToolRequestSchema, async (request) => {
10043 |       if (request.params.name === "calculate_sum") {
10044 |         const { a, b } = request.params.arguments;
10045 |         return {
10046 |           content: [
10047 |             {
10048 |               type: "text",
10049 |               text: String(a + b)
10050 |             }
10051 |           ]
10052 |         };
10053 |       }
10054 |       throw new Error("Tool not found");
10055 |     });
10056 |     ```
10057 |   </Tab>
10058 | 
10059 |   <Tab title="Python">
10060 |     ```python
10061 |     app = Server("example-server")
10062 | 
10063 |     @app.list_tools()
10064 |     async def list_tools() -> list[types.Tool]:
10065 |         return [
10066 |             types.Tool(
10067 |                 name="calculate_sum",
10068 |                 description="Add two numbers together",
10069 |                 inputSchema={
10070 |                     "type": "object",
10071 |                     "properties": {
10072 |                         "a": {"type": "number"},
10073 |                         "b": {"type": "number"}
10074 |                     },
10075 |                     "required": ["a", "b"]
10076 |                 }
10077 |             )
10078 |         ]
10079 | 
10080 |     @app.call_tool()
10081 |     async def call_tool(
10082 |         name: str,
10083 |         arguments: dict
10084 |     ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
10085 |         if name == "calculate_sum":
10086 |             a = arguments["a"]
10087 |             b = arguments["b"]
10088 |             result = a + b
10089 |             return [types.TextContent(type="text", text=str(result))]
10090 |         raise ValueError(f"Tool not found: {name}")
10091 |     ```
10092 |   </Tab>
10093 | </Tabs>
10094 | 
10095 | ## Example tool patterns
10096 | 
10097 | Here are some examples of types of tools that a server could provide:
10098 | 
10099 | ### System operations
10100 | 
10101 | Tools that interact with the local system:
10102 | 
10103 | ```typescript
10104 | {
10105 |   name: "execute_command",
10106 |   description: "Run a shell command",
10107 |   inputSchema: {
10108 |     type: "object",
10109 |     properties: {
10110 |       command: { type: "string" },
10111 |       args: { type: "array", items: { type: "string" } }
10112 |     }
10113 |   }
10114 | }
10115 | ```
10116 | 
10117 | ### API integrations
10118 | 
10119 | Tools that wrap external APIs:
10120 | 
10121 | ```typescript
10122 | {
10123 |   name: "github_create_issue",
10124 |   description: "Create a GitHub issue",
10125 |   inputSchema: {
10126 |     type: "object",
10127 |     properties: {
10128 |       title: { type: "string" },
10129 |       body: { type: "string" },
10130 |       labels: { type: "array", items: { type: "string" } }
10131 |     }
10132 |   }
10133 | }
10134 | ```
10135 | 
10136 | ### Data processing
10137 | 
10138 | Tools that transform or analyze data:
10139 | 
10140 | ```typescript
10141 | {
10142 |   name: "analyze_csv",
10143 |   description: "Analyze a CSV file",
10144 |   inputSchema: {
10145 |     type: "object",
10146 |     properties: {
10147 |       filepath: { type: "string" },
10148 |       operations: {
10149 |         type: "array",
10150 |         items: {
10151 |           enum: ["sum", "average", "count"]
10152 |         }
10153 |       }
10154 |     }
10155 |   }
10156 | }
10157 | ```
10158 | 
10159 | ## Best practices
10160 | 
10161 | When implementing tools:
10162 | 
10163 | 1.  Provide clear, descriptive names and descriptions
10164 | 2.  Use detailed JSON Schema definitions for parameters
10165 | 3.  Include examples in tool descriptions to demonstrate how the model should use them
10166 | 4.  Implement proper error handling and validation
10167 | 5.  Use progress reporting for long operations
10168 | 6.  Keep tool operations focused and atomic
10169 | 7.  Document expected return value structures
10170 | 8.  Implement proper timeouts
10171 | 9.  Consider rate limiting for resource-intensive operations
10172 | 10. Log tool usage for debugging and monitoring
10173 | 
10174 | ## Security considerations
10175 | 
10176 | When exposing tools:
10177 | 
10178 | ### Input validation
10179 | 
10180 | *   Validate all parameters against the schema
10181 | *   Sanitize file paths and system commands
10182 | *   Validate URLs and external identifiers
10183 | *   Check parameter sizes and ranges
10184 | *   Prevent command injection
10185 | 
10186 | ### Access control
10187 | 
10188 | *   Implement authentication where needed
10189 | *   Use appropriate authorization checks
10190 | *   Audit tool usage
10191 | *   Rate limit requests
10192 | *   Monitor for abuse
10193 | 
10194 | ### Error handling
10195 | 
10196 | *   Don't expose internal errors to clients
10197 | *   Log security-relevant errors
10198 | *   Handle timeouts appropriately
10199 | *   Clean up resources after errors
10200 | *   Validate return values
10201 | 
10202 | ## Tool discovery and updates
10203 | 
10204 | MCP supports dynamic tool discovery:
10205 | 
10206 | 1.  Clients can list available tools at any time
10207 | 2.  Servers can notify clients when tools change using `notifications/tools/list_changed`
10208 | 3.  Tools can be added or removed during runtime
10209 | 4.  Tool definitions can be updated (though this should be done carefully)
10210 | 
10211 | ## Error handling
10212 | 
10213 | Tool errors should be reported within the result object, not as MCP protocol-level errors. This allows the LLM to see and potentially handle the error. When a tool encounters an error:
10214 | 
10215 | 1.  Set `isError` to `true` in the result
10216 | 2.  Include error details in the `content` array
10217 | 
10218 | Here's an example of proper error handling for tools:
10219 | 
10220 | <Tabs>
10221 |   <Tab title="TypeScript">
10222 |     ```typescript
10223 |     try {
10224 |       // Tool operation
10225 |       const result = performOperation();
10226 |       return {
10227 |         content: [
10228 |           {
10229 |             type: "text",
10230 |             text: `Operation successful: ${result}`
10231 |           }
10232 |         ]
10233 |       };
10234 |     } catch (error) {
10235 |       return {
10236 |         isError: true,
10237 |         content: [
10238 |           {
10239 |             type: "text",
10240 |             text: `Error: ${error.message}`
10241 |           }
10242 |         ]
10243 |       };
10244 |     }
10245 |     ```
10246 |   </Tab>
10247 | 
10248 |   <Tab title="Python">
10249 |     ```python
10250 |     try:
10251 |         # Tool operation
10252 |         result = perform_operation()
10253 |         return types.CallToolResult(
10254 |             content=[
10255 |                 types.TextContent(
10256 |                     type="text",
10257 |                     text=f"Operation successful: {result}"
10258 |                 )
10259 |             ]
10260 |         )
10261 |     except Exception as error:
10262 |         return types.CallToolResult(
10263 |             isError=True,
10264 |             content=[
10265 |                 types.TextContent(
10266 |                     type="text",
10267 |                     text=f"Error: {str(error)}"
10268 |                 )
10269 |             ]
10270 |         )
10271 |     ```
10272 |   </Tab>
10273 | </Tabs>
10274 | 
10275 | This approach allows the LLM to see that an error occurred and potentially take corrective action or request human intervention.
10276 | 
10277 | ## Testing tools
10278 | 
10279 | A comprehensive testing strategy for MCP tools should cover:
10280 | 
10281 | *   **Functional testing**: Verify tools execute correctly with valid inputs and handle invalid inputs appropriately
10282 | *   **Integration testing**: Test tool interaction with external systems using both real and mocked dependencies
10283 | *   **Security testing**: Validate authentication, authorization, input sanitization, and rate limiting
10284 | *   **Performance testing**: Check behavior under load, timeout handling, and resource cleanup
10285 | *   **Error handling**: Ensure tools properly report errors through the MCP protocol and clean up resources
10286 | 
10287 | 
10288 | # Transports
10289 | Source: https://modelcontextprotocol.io/docs/concepts/transports
10290 | 
10291 | Learn about MCP's communication mechanisms
10292 | 
10293 | Transports in the Model Context Protocol (MCP) provide the foundation for communication between clients and servers. A transport handles the underlying mechanics of how messages are sent and received.
10294 | 
10295 | ## Message Format
10296 | 
10297 | MCP uses [JSON-RPC](https://www.jsonrpc.org/) 2.0 as its wire format. The transport layer is responsible for converting MCP protocol messages into JSON-RPC format for transmission and converting received JSON-RPC messages back into MCP protocol messages.
10298 | 
10299 | There are three types of JSON-RPC messages used:
10300 | 
10301 | ### Requests
10302 | 
10303 | ```typescript
10304 | {
10305 |   jsonrpc: "2.0",
10306 |   id: number | string,
10307 |   method: string,
10308 |   params?: object
10309 | }
10310 | ```
10311 | 
10312 | ### Responses
10313 | 
10314 | ```typescript
10315 | {
10316 |   jsonrpc: "2.0",
10317 |   id: number | string,
10318 |   result?: object,
10319 |   error?: {
10320 |     code: number,
10321 |     message: string,
10322 |     data?: unknown
10323 |   }
10324 | }
10325 | ```
10326 | 
10327 | ### Notifications
10328 | 
10329 | ```typescript
10330 | {
10331 |   jsonrpc: "2.0",
10332 |   method: string,
10333 |   params?: object
10334 | }
10335 | ```
10336 | 
10337 | ## Built-in Transport Types
10338 | 
10339 | MCP includes two standard transport implementations:
10340 | 
10341 | ### Standard Input/Output (stdio)
10342 | 
10343 | The stdio transport enables communication through standard input and output streams. This is particularly useful for local integrations and command-line tools.
10344 | 
10345 | Use stdio when:
10346 | 
10347 | *   Building command-line tools
10348 | *   Implementing local integrations
10349 | *   Needing simple process communication
10350 | *   Working with shell scripts
10351 | 
10352 | <Tabs>
10353 |   <Tab title="TypeScript (Server)">
10354 |     ```typescript
10355 |     const server = new Server({
10356 |       name: "example-server",
10357 |       version: "1.0.0"
10358 |     }, {
10359 |       capabilities: {}
10360 |     });
10361 | 
10362 |     const transport = new StdioServerTransport();
10363 |     await server.connect(transport);
10364 |     ```
10365 |   </Tab>
10366 | 
10367 |   <Tab title="TypeScript (Client)">
10368 |     ```typescript
10369 |     const client = new Client({
10370 |       name: "example-client",
10371 |       version: "1.0.0"
10372 |     }, {
10373 |       capabilities: {}
10374 |     });
10375 | 
10376 |     const transport = new StdioClientTransport({
10377 |       command: "./server",
10378 |       args: ["--option", "value"]
10379 |     });
10380 |     await client.connect(transport);
10381 |     ```
10382 |   </Tab>
10383 | 
10384 |   <Tab title="Python (Server)">
10385 |     ```python
10386 |     app = Server("example-server")
10387 | 
10388 |     async with stdio_server() as streams:
10389 |         await app.run(
10390 |             streams[0],
10391 |             streams[1],
10392 |             app.create_initialization_options()
10393 |         )
10394 |     ```
10395 |   </Tab>
10396 | 
10397 |   <Tab title="Python (Client)">
10398 |     ```python
10399 |     params = StdioServerParameters(
10400 |         command="./server",
10401 |         args=["--option", "value"]
10402 |     )
10403 | 
10404 |     async with stdio_client(params) as streams:
10405 |         async with ClientSession(streams[0], streams[1]) as session:
10406 |             await session.initialize()
10407 |     ```
10408 |   </Tab>
10409 | </Tabs>
10410 | 
10411 | ### Server-Sent Events (SSE)
10412 | 
10413 | SSE transport enables server-to-client streaming with HTTP POST requests for client-to-server communication.
10414 | 
10415 | Use SSE when:
10416 | 
10417 | *   Only server-to-client streaming is needed
10418 | *   Working with restricted networks
10419 | *   Implementing simple updates
10420 | 
10421 | <Tabs>
10422 |   <Tab title="TypeScript (Server)">
10423 |     ```typescript
10424 |     import express from "express";
10425 | 
10426 |     const app = express();
10427 | 
10428 |     const server = new Server({
10429 |       name: "example-server",
10430 |       version: "1.0.0"
10431 |     }, {
10432 |       capabilities: {}
10433 |     });
10434 | 
10435 |     let transport: SSEServerTransport | null = null;
10436 | 
10437 |     app.get("/sse", (req, res) => {
10438 |       transport = new SSEServerTransport("/messages", res);
10439 |       server.connect(transport);
10440 |     });
10441 | 
10442 |     app.post("/messages", (req, res) => {
10443 |       if (transport) {
10444 |         transport.handlePostMessage(req, res);
10445 |       }
10446 |     });
10447 | 
10448 |     app.listen(3000);
10449 |     ```
10450 |   </Tab>
10451 | 
10452 |   <Tab title="TypeScript (Client)">
10453 |     ```typescript
10454 |     const client = new Client({
10455 |       name: "example-client",
10456 |       version: "1.0.0"
10457 |     }, {
10458 |       capabilities: {}
10459 |     });
10460 | 
10461 |     const transport = new SSEClientTransport(
10462 |       new URL("http://localhost:3000/sse")
10463 |     );
10464 |     await client.connect(transport);
10465 |     ```
10466 |   </Tab>
10467 | 
10468 |   <Tab title="Python (Server)">
10469 |     ```python
10470 |     from mcp.server.sse import SseServerTransport
10471 |     from starlette.applications import Starlette
10472 |     from starlette.routing import Route
10473 | 
10474 |     app = Server("example-server")
10475 |     sse = SseServerTransport("/messages")
10476 | 
10477 |     async def handle_sse(scope, receive, send):
10478 |         async with sse.connect_sse(scope, receive, send) as streams:
10479 |             await app.run(streams[0], streams[1], app.create_initialization_options())
10480 | 
10481 |     async def handle_messages(scope, receive, send):
10482 |         await sse.handle_post_message(scope, receive, send)
10483 | 
10484 |     starlette_app = Starlette(
10485 |         routes=[
10486 |             Route("/sse", endpoint=handle_sse),
10487 |             Route("/messages", endpoint=handle_messages, methods=["POST"]),
10488 |         ]
10489 |     )
10490 |     ```
10491 |   </Tab>
10492 | 
10493 |   <Tab title="Python (Client)">
10494 |     ```python
10495 |     async with sse_client("http://localhost:8000/sse") as streams:
10496 |         async with ClientSession(streams[0], streams[1]) as session:
10497 |             await session.initialize()
10498 |     ```
10499 |   </Tab>
10500 | </Tabs>
10501 | 
10502 | ## Custom Transports
10503 | 
10504 | MCP makes it easy to implement custom transports for specific needs. Any transport implementation just needs to conform to the Transport interface:
10505 | 
10506 | You can implement custom transports for:
10507 | 
10508 | *   Custom network protocols
10509 | *   Specialized communication channels
10510 | *   Integration with existing systems
10511 | *   Performance optimization
10512 | 
10513 | <Tabs>
10514 |   <Tab title="TypeScript">
10515 |     ```typescript
10516 |     interface Transport {
10517 |       // Start processing messages
10518 |       start(): Promise<void>;
10519 | 
10520 |       // Send a JSON-RPC message
10521 |       send(message: JSONRPCMessage): Promise<void>;
10522 | 
10523 |       // Close the connection
10524 |       close(): Promise<void>;
10525 | 
10526 |       // Callbacks
10527 |       onclose?: () => void;
10528 |       onerror?: (error: Error) => void;
10529 |       onmessage?: (message: JSONRPCMessage) => void;
10530 |     }
10531 |     ```
10532 |   </Tab>
10533 | 
10534 |   <Tab title="Python">
10535 |     Note that while MCP Servers are often implemented with asyncio, we recommend
10536 |     implementing low-level interfaces like transports with `anyio` for wider compatibility.
10537 | 
10538 |     ```python
10539 |     @contextmanager
10540 |     async def create_transport(
10541 |         read_stream: MemoryObjectReceiveStream[JSONRPCMessage | Exception],
10542 |         write_stream: MemoryObjectSendStream[JSONRPCMessage]
10543 |     ):
10544 |         """
10545 |         Transport interface for MCP.
10546 | 
10547 |         Args:
10548 |             read_stream: Stream to read incoming messages from
10549 |             write_stream: Stream to write outgoing messages to
10550 |         """
10551 |         async with anyio.create_task_group() as tg:
10552 |             try:
10553 |                 # Start processing messages
10554 |                 tg.start_soon(lambda: process_messages(read_stream))
10555 | 
10556 |                 # Send messages
10557 |                 async with write_stream:
10558 |                     yield write_stream
10559 | 
10560 |             except Exception as exc:
10561 |                 # Handle errors
10562 |                 raise exc
10563 |             finally:
10564 |                 # Clean up
10565 |                 tg.cancel_scope.cancel()
10566 |                 await write_stream.aclose()
10567 |                 await read_stream.aclose()
10568 |     ```
10569 |   </Tab>
10570 | </Tabs>
10571 | 
10572 | ## Error Handling
10573 | 
10574 | Transport implementations should handle various error scenarios:
10575 | 
10576 | 1.  Connection errors
10577 | 2.  Message parsing errors
10578 | 3.  Protocol errors
10579 | 4.  Network timeouts
10580 | 5.  Resource cleanup
10581 | 
10582 | Example error handling:
10583 | 
10584 | <Tabs>
10585 |   <Tab title="TypeScript">
10586 |     ```typescript
10587 |     class ExampleTransport implements Transport {
10588 |       async start() {
10589 |         try {
10590 |           // Connection logic
10591 |         } catch (error) {
10592 |           this.onerror?.(new Error(`Failed to connect: ${error}`));
10593 |           throw error;
10594 |         }
10595 |       }
10596 | 
10597 |       async send(message: JSONRPCMessage) {
10598 |         try {
10599 |           // Sending logic
10600 |         } catch (error) {
10601 |           this.onerror?.(new Error(`Failed to send message: ${error}`));
10602 |           throw error;
10603 |         }
10604 |       }
10605 |     }
10606 |     ```
10607 |   </Tab>
10608 | 
10609 |   <Tab title="Python">
10610 |     Note that while MCP Servers are often implemented with asyncio, we recommend
10611 |     implementing low-level interfaces like transports with `anyio` for wider compatibility.
10612 | 
10613 |     ```python
10614 |     @contextmanager
10615 |     async def example_transport(scope: Scope, receive: Receive, send: Send):
10616 |         try:
10617 |             # Create streams for bidirectional communication
10618 |             read_stream_writer, read_stream = anyio.create_memory_object_stream(0)
10619 |             write_stream, write_stream_reader = anyio.create_memory_object_stream(0)
10620 | 
10621 |             async def message_handler():
10622 |                 try:
10623 |                     async with read_stream_writer:
10624 |                         # Message handling logic
10625 |                         pass
10626 |                 except Exception as exc:
10627 |                     logger.error(f"Failed to handle message: {exc}")
10628 |                     raise exc
10629 | 
10630 |             async with anyio.create_task_group() as tg:
10631 |                 tg.start_soon(message_handler)
10632 |                 try:
10633 |                     # Yield streams for communication
10634 |                     yield read_stream, write_stream
10635 |                 except Exception as exc:
10636 |                     logger.error(f"Transport error: {exc}")
10637 |                     raise exc
10638 |                 finally:
10639 |                     tg.cancel_scope.cancel()
10640 |                     await write_stream.aclose()
10641 |                     await read_stream.aclose()
10642 |         except Exception as exc:
10643 |             logger.error(f"Failed to initialize transport: {exc}")
10644 |             raise exc
10645 |     ```
10646 |   </Tab>
10647 | </Tabs>
10648 | 
10649 | ## Best Practices
10650 | 
10651 | When implementing or using MCP transport:
10652 | 
10653 | 1.  Handle connection lifecycle properly
10654 | 2.  Implement proper error handling
10655 | 3.  Clean up resources on connection close
10656 | 4.  Use appropriate timeouts
10657 | 5.  Validate messages before sending
10658 | 6.  Log transport events for debugging
10659 | 7.  Implement reconnection logic when appropriate
10660 | 8.  Handle backpressure in message queues
10661 | 9.  Monitor connection health
10662 | 10. Implement proper security measures
10663 | 
10664 | ## Security Considerations
10665 | 
10666 | When implementing transport:
10667 | 
10668 | ### Authentication and Authorization
10669 | 
10670 | *   Implement proper authentication mechanisms
10671 | *   Validate client credentials
10672 | *   Use secure token handling
10673 | *   Implement authorization checks
10674 | 
10675 | ### Data Security
10676 | 
10677 | *   Use TLS for network transport
10678 | *   Encrypt sensitive data
10679 | *   Validate message integrity
10680 | *   Implement message size limits
10681 | *   Sanitize input data
10682 | 
10683 | ### Network Security
10684 | 
10685 | *   Implement rate limiting
10686 | *   Use appropriate timeouts
10687 | *   Handle denial of service scenarios
10688 | *   Monitor for unusual patterns
10689 | *   Implement proper firewall rules
10690 | 
10691 | ## Debugging Transport
10692 | 
10693 | Tips for debugging transport issues:
10694 | 
10695 | 1.  Enable debug logging
10696 | 2.  Monitor message flow
10697 | 3.  Check connection states
10698 | 4.  Validate message formats
10699 | 5.  Test error scenarios
10700 | 6.  Use network analysis tools
10701 | 7.  Implement health checks
10702 | 8.  Monitor resource usage
10703 | 9.  Test edge cases
10704 | 10. Use proper error tracking
10705 | 
10706 | 
10707 | # Debugging
10708 | Source: https://modelcontextprotocol.io/docs/tools/debugging
10709 | 
10710 | A comprehensive guide to debugging Model Context Protocol (MCP) integrations
10711 | 
10712 | Effective debugging is essential when developing MCP servers or integrating them with applications. This guide covers the debugging tools and approaches available in the MCP ecosystem.
10713 | 
10714 | <Info>
10715 |   This guide is for macOS. Guides for other platforms are coming soon.
10716 | </Info>
10717 | 
10718 | ## Debugging tools overview
10719 | 
10720 | MCP provides several tools for debugging at different levels:
10721 | 
10722 | 1.  **MCP Inspector**
10723 |     *   Interactive debugging interface
10724 |     *   Direct server testing
10725 |     *   See the [Inspector guide](/docs/tools/inspector) for details
10726 | 
10727 | 2.  **Claude Desktop Developer Tools**
10728 |     *   Integration testing
10729 |     *   Log collection
10730 |     *   Chrome DevTools integration
10731 | 
10732 | 3.  **Server Logging**
10733 |     *   Custom logging implementations
10734 |     *   Error tracking
10735 |     *   Performance monitoring
10736 | 
10737 | ## Debugging in Claude Desktop
10738 | 
10739 | ### Checking server status
10740 | 
10741 | The Claude.app interface provides basic server status information:
10742 | 
10743 | 1.  Click the <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/claude-desktop-mcp-plug-icon.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon to view:
10744 |     *   Connected servers
10745 |     *   Available prompts and resources
10746 | 
10747 | 2.  Click the <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/claude-desktop-mcp-hammer-icon.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon to view:
10748 |     *   Tools made available to the model
10749 | 
10750 | ### Viewing logs
10751 | 
10752 | Review detailed MCP logs from Claude Desktop:
10753 | 
10754 | ```bash
10755 | # Follow logs in real-time
10756 | tail -n 20 -F ~/Library/Logs/Claude/mcp*.log
10757 | ```
10758 | 
10759 | The logs capture:
10760 | 
10761 | *   Server connection events
10762 | *   Configuration issues
10763 | *   Runtime errors
10764 | *   Message exchanges
10765 | 
10766 | ### Using Chrome DevTools
10767 | 
10768 | Access Chrome's developer tools inside Claude Desktop to investigate client-side errors:
10769 | 
10770 | 1.  Create a `developer_settings.json` file with `allowDevTools` set to true:
10771 | 
10772 | ```bash
10773 | echo '{"allowDevTools": true}' > ~/Library/Application\ Support/Claude/developer_settings.json
10774 | ```
10775 | 
10776 | 2.  Open DevTools: `Command-Option-Shift-i`
10777 | 
10778 | Note: You'll see two DevTools windows:
10779 | 
10780 | *   Main content window
10781 | *   App title bar window
10782 | 
10783 | Use the Console panel to inspect client-side errors.
10784 | 
10785 | Use the Network panel to inspect:
10786 | 
10787 | *   Message payloads
10788 | *   Connection timing
10789 | 
10790 | ## Common issues
10791 | 
10792 | ### Working directory
10793 | 
10794 | When using MCP servers with Claude Desktop:
10795 | 
10796 | *   The working directory for servers launched via `claude_desktop_config.json` may be undefined (like `/` on macOS) since Claude Desktop could be started from anywhere
10797 | *   Always use absolute paths in your configuration and `.env` files to ensure reliable operation
10798 | *   For testing servers directly via command line, the working directory will be where you run the command
10799 | 
10800 | For example in `claude_desktop_config.json`, use:
10801 | 
10802 | ```json
10803 | {
10804 |   "command": "npx",
10805 |   "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/username/data"]
10806 | }
10807 | ```
10808 | 
10809 | Instead of relative paths like `./data`
10810 | 
10811 | ### Environment variables
10812 | 
10813 | MCP servers inherit only a subset of environment variables automatically, like `USER`, `HOME`, and `PATH`.
10814 | 
10815 | To override the default variables or provide your own, you can specify an `env` key in `claude_desktop_config.json`:
10816 | 
10817 | ```json
10818 | {
10819 |   "myserver": {
10820 |     "command": "mcp-server-myapp",
10821 |     "env": {
10822 |       "MYAPP_API_KEY": "some_key",
10823 |     }
10824 |   }
10825 | }
10826 | ```
10827 | 
10828 | ### Server initialization
10829 | 
10830 | Common initialization problems:
10831 | 
10832 | 1.  **Path Issues**
10833 |     *   Incorrect server executable path
10834 |     *   Missing required files
10835 |     *   Permission problems
10836 |     *   Try using an absolute path for `command`
10837 | 
10838 | 2.  **Configuration Errors**
10839 |     *   Invalid JSON syntax
10840 |     *   Missing required fields
10841 |     *   Type mismatches
10842 | 
10843 | 3.  **Environment Problems**
10844 |     *   Missing environment variables
10845 |     *   Incorrect variable values
10846 |     *   Permission restrictions
10847 | 
10848 | ### Connection problems
10849 | 
10850 | When servers fail to connect:
10851 | 
10852 | 1.  Check Claude Desktop logs
10853 | 2.  Verify server process is running
10854 | 3.  Test standalone with [Inspector](/docs/tools/inspector)
10855 | 4.  Verify protocol compatibility
10856 | 
10857 | ## Implementing logging
10858 | 
10859 | ### Server-side logging
10860 | 
10861 | When building a server that uses the local stdio [transport](/docs/concepts/transports), all messages logged to stderr (standard error) will be captured by the host application (e.g., Claude Desktop) automatically.
10862 | 
10863 | <Warning>
10864 |   Local MCP servers should not log messages to stdout (standard out), as this will interfere with protocol operation.
10865 | </Warning>
10866 | 
10867 | For all [transports](/docs/concepts/transports), you can also provide logging to the client by sending a log message notification:
10868 | 
10869 | <Tabs>
10870 |   <Tab title="Python">
10871 |     ```python
10872 |     server.request_context.session.send_log_message(
10873 |       level="info",
10874 |       data="Server started successfully",
10875 |     )
10876 |     ```
10877 |   </Tab>
10878 | 
10879 |   <Tab title="TypeScript">
10880 |     ```typescript
10881 |     server.sendLoggingMessage({
10882 |       level: "info",
10883 |       data: "Server started successfully",
10884 |     });
10885 |     ```
10886 |   </Tab>
10887 | </Tabs>
10888 | 
10889 | Important events to log:
10890 | 
10891 | *   Initialization steps
10892 | *   Resource access
10893 | *   Tool execution
10894 | *   Error conditions
10895 | *   Performance metrics
10896 | 
10897 | ### Client-side logging
10898 | 
10899 | In client applications:
10900 | 
10901 | 1.  Enable debug logging
10902 | 2.  Monitor network traffic
10903 | 3.  Track message exchanges
10904 | 4.  Record error states
10905 | 
10906 | ## Debugging workflow
10907 | 
10908 | ### Development cycle
10909 | 
10910 | 1.  Initial Development
10911 |     *   Use [Inspector](/docs/tools/inspector) for basic testing
10912 |     *   Implement core functionality
10913 |     *   Add logging points
10914 | 
10915 | 2.  Integration Testing
10916 |     *   Test in Claude Desktop
10917 |     *   Monitor logs
10918 |     *   Check error handling
10919 | 
10920 | ### Testing changes
10921 | 
10922 | To test changes efficiently:
10923 | 
10924 | *   **Configuration changes**: Restart Claude Desktop
10925 | *   **Server code changes**: Use Command-R to reload
10926 | *   **Quick iteration**: Use [Inspector](/docs/tools/inspector) during development
10927 | 
10928 | ## Best practices
10929 | 
10930 | ### Logging strategy
10931 | 
10932 | 1.  **Structured Logging**
10933 |     *   Use consistent formats
10934 |     *   Include context
10935 |     *   Add timestamps
10936 |     *   Track request IDs
10937 | 
10938 | 2.  **Error Handling**
10939 |     *   Log stack traces
10940 |     *   Include error context
10941 |     *   Track error patterns
10942 |     *   Monitor recovery
10943 | 
10944 | 3.  **Performance Tracking**
10945 |     *   Log operation timing
10946 |     *   Monitor resource usage
10947 |     *   Track message sizes
10948 |     *   Measure latency
10949 | 
10950 | ### Security considerations
10951 | 
10952 | When debugging:
10953 | 
10954 | 1.  **Sensitive Data**
10955 |     *   Sanitize logs
10956 |     *   Protect credentials
10957 |     *   Mask personal information
10958 | 
10959 | 2.  **Access Control**
10960 |     *   Verify permissions
10961 |     *   Check authentication
10962 |     *   Monitor access patterns
10963 | 
10964 | ## Getting help
10965 | 
10966 | When encountering issues:
10967 | 
10968 | 1.  **First Steps**
10969 |     *   Check server logs
10970 |     *   Test with [Inspector](/docs/tools/inspector)
10971 |     *   Review configuration
10972 |     *   Verify environment
10973 | 
10974 | 2.  **Support Channels**
10975 |     *   GitHub issues
10976 |     *   GitHub discussions
10977 | 
10978 | 3.  **Providing Information**
10979 |     *   Log excerpts
10980 |     *   Configuration files
10981 |     *   Steps to reproduce
10982 |     *   Environment details
10983 | 
10984 | ## Next steps
10985 | 
10986 | <CardGroup cols={2}>
10987 |   <Card title="MCP Inspector" icon="magnifying-glass" href="/docs/tools/inspector">
10988 |     Learn to use the MCP Inspector
10989 |   </Card>
10990 | </CardGroup>
10991 | 
10992 | 
10993 | # Inspector
10994 | Source: https://modelcontextprotocol.io/docs/tools/inspector
10995 | 
10996 | In-depth guide to using the MCP Inspector for testing and debugging Model Context Protocol servers
10997 | 
10998 | The [MCP Inspector](https://github.com/modelcontextprotocol/inspector) is an interactive developer tool for testing and debugging MCP servers. While the [Debugging Guide](/docs/tools/debugging) covers the Inspector as part of the overall debugging toolkit, this document provides a detailed exploration of the Inspector's features and capabilities.
10999 | 
11000 | ## Getting started
11001 | 
11002 | ### Installation and basic usage
11003 | 
11004 | The Inspector runs directly through `npx` without requiring installation:
11005 | 
11006 | ```bash
11007 | npx @modelcontextprotocol/inspector <command>
11008 | ```
11009 | 
11010 | ```bash
11011 | npx @modelcontextprotocol/inspector <command> <arg1> <arg2>
11012 | ```
11013 | 
11014 | #### Inspecting servers from NPM or PyPi
11015 | 
11016 | A common way to start server packages from [NPM](https://npmjs.com) or [PyPi](https://pypi.com).
11017 | 
11018 | <Tabs>
11019 |   <Tab title="NPM package">
11020 |     ```bash
11021 |     npx -y @modelcontextprotocol/inspector npx <package-name> <args>
11022 |     # For example
11023 |     npx -y @modelcontextprotocol/inspector npx server-postgres postgres://127.0.0.1/testdb
11024 |     ```
11025 |   </Tab>
11026 | 
11027 |   <Tab title="PyPi package">
11028 |     ```bash
11029 |     npx @modelcontextprotocol/inspector uvx <package-name> <args>
11030 |     # For example
11031 |     npx @modelcontextprotocol/inspector uvx mcp-server-git --repository ~/code/mcp/servers.git
11032 |     ```
11033 |   </Tab>
11034 | </Tabs>
11035 | 
11036 | #### Inspecting locally developed servers
11037 | 
11038 | To inspect servers locally developed or downloaded as a repository, the most common
11039 | way is:
11040 | 
11041 | <Tabs>
11042 |   <Tab title="TypeScript">
11043 |     ```bash
11044 |     npx @modelcontextprotocol/inspector node path/to/server/index.js args...
11045 |     ```
11046 |   </Tab>
11047 | 
11048 |   <Tab title="Python">
11049 |     ```bash
11050 |     npx @modelcontextprotocol/inspector \
11051 |       uv \
11052 |       --directory path/to/server \
11053 |       run \
11054 |       package-name \
11055 |       args...
11056 |     ```
11057 |   </Tab>
11058 | </Tabs>
11059 | 
11060 | Please carefully read any attached README for the most accurate instructions.
11061 | 
11062 | ## Feature overview
11063 | 
11064 | <Frame caption="The MCP Inspector interface">
11065 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/mcp-inspector.png" />
11066 | </Frame>
11067 | 
11068 | The Inspector provides several features for interacting with your MCP server:
11069 | 
11070 | ### Server connection pane
11071 | 
11072 | *   Allows selecting the [transport](/docs/concepts/transports) for connecting to the server
11073 | *   For local servers, supports customizing the command-line arguments and environment
11074 | 
11075 | ### Resources tab
11076 | 
11077 | *   Lists all available resources
11078 | *   Shows resource metadata (MIME types, descriptions)
11079 | *   Allows resource content inspection
11080 | *   Supports subscription testing
11081 | 
11082 | ### Prompts tab
11083 | 
11084 | *   Displays available prompt templates
11085 | *   Shows prompt arguments and descriptions
11086 | *   Enables prompt testing with custom arguments
11087 | *   Previews generated messages
11088 | 
11089 | ### Tools tab
11090 | 
11091 | *   Lists available tools
11092 | *   Shows tool schemas and descriptions
11093 | *   Enables tool testing with custom inputs
11094 | *   Displays tool execution results
11095 | 
11096 | ### Notifications pane
11097 | 
11098 | *   Presents all logs recorded from the server
11099 | *   Shows notifications received from the server
11100 | 
11101 | ## Best practices
11102 | 
11103 | ### Development workflow
11104 | 
11105 | 1.  Start Development
11106 |     *   Launch Inspector with your server
11107 |     *   Verify basic connectivity
11108 |     *   Check capability negotiation
11109 | 
11110 | 2.  Iterative testing
11111 |     *   Make server changes
11112 |     *   Rebuild the server
11113 |     *   Reconnect the Inspector
11114 |     *   Test affected features
11115 |     *   Monitor messages
11116 | 
11117 | 3.  Test edge cases
11118 |     *   Invalid inputs
11119 |     *   Missing prompt arguments
11120 |     *   Concurrent operations
11121 |     *   Verify error handling and error responses
11122 | 
11123 | ## Next steps
11124 | 
11125 | <CardGroup cols={2}>
11126 |   <Card title="Inspector Repository" icon="github" href="https://github.com/modelcontextprotocol/inspector">
11127 |     Check out the MCP Inspector source code
11128 |   </Card>
11129 | 
11130 |   <Card title="Debugging Guide" icon="bug" href="/docs/tools/debugging">
11131 |     Learn about broader debugging strategies
11132 |   </Card>
11133 | </CardGroup>
11134 | 
11135 | 
11136 | # Example Servers
11137 | Source: https://modelcontextprotocol.io/examples
11138 | 
11139 | A list of example servers and implementations
11140 | 
11141 | This page showcases various Model Context Protocol (MCP) servers that demonstrate the protocol's capabilities and versatility. These servers enable Large Language Models (LLMs) to securely access tools and data sources.
11142 | 
11143 | ## Reference implementations
11144 | 
11145 | These official reference servers demonstrate core MCP features and SDK usage:
11146 | 
11147 | ### Data and file systems
11148 | 
11149 | * **[Filesystem](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem)** - Secure file operations with configurable access controls
11150 | * **[PostgreSQL](https://github.com/modelcontextprotocol/servers/tree/main/src/postgres)** - Read-only database access with schema inspection capabilities
11151 | * **[SQLite](https://github.com/modelcontextprotocol/servers/tree/main/src/sqlite)** - Database interaction and business intelligence features
11152 | * **[Google Drive](https://github.com/modelcontextprotocol/servers/tree/main/src/gdrive)** - File access and search capabilities for Google Drive
11153 | 
11154 | ### Development tools
11155 | 
11156 | * **[Git](https://github.com/modelcontextprotocol/servers/tree/main/src/git)** - Tools to read, search, and manipulate Git repositories
11157 | * **[GitHub](https://github.com/modelcontextprotocol/servers/tree/main/src/github)** - Repository management, file operations, and GitHub API integration
11158 | * **[GitLab](https://github.com/modelcontextprotocol/servers/tree/main/src/gitlab)** - GitLab API integration enabling project management
11159 | * **[Sentry](https://github.com/modelcontextprotocol/servers/tree/main/src/sentry)** - Retrieving and analyzing issues from Sentry.io
11160 | 
11161 | ### Web and browser automation
11162 | 
11163 | * **[Brave Search](https://github.com/modelcontextprotocol/servers/tree/main/src/brave-search)** - Web and local search using Brave's Search API
11164 | * **[Fetch](https://github.com/modelcontextprotocol/servers/tree/main/src/fetch)** - Web content fetching and conversion optimized for LLM usage
11165 | * **[Puppeteer](https://github.com/modelcontextprotocol/servers/tree/main/src/puppeteer)** - Browser automation and web scraping capabilities
11166 | 
11167 | ### Productivity and communication
11168 | 
11169 | * **[Slack](https://github.com/modelcontextprotocol/servers/tree/main/src/slack)** - Channel management and messaging capabilities
11170 | * **[Google Maps](https://github.com/modelcontextprotocol/servers/tree/main/src/google-maps)** - Location services, directions, and place details
11171 | * **[Memory](https://github.com/modelcontextprotocol/servers/tree/main/src/memory)** - Knowledge graph-based persistent memory system
11172 | 
11173 | ### AI and specialized tools
11174 | 
11175 | * **[EverArt](https://github.com/modelcontextprotocol/servers/tree/main/src/everart)** - AI image generation using various models
11176 | * **[Sequential Thinking](https://github.com/modelcontextprotocol/servers/tree/main/src/sequentialthinking)** - Dynamic problem-solving through thought sequences
11177 | * **[AWS KB Retrieval](https://github.com/modelcontextprotocol/servers/tree/main/src/aws-kb-retrieval-server)** - Retrieval from AWS Knowledge Base using Bedrock Agent Runtime
11178 | 
11179 | ## Official integrations
11180 | 
11181 | These MCP servers are maintained by companies for their platforms:
11182 | 
11183 | * **[Axiom](https://github.com/axiomhq/mcp-server-axiom)** - Query and analyze logs, traces, and event data using natural language
11184 | * **[Browserbase](https://github.com/browserbase/mcp-server-browserbase)** - Automate browser interactions in the cloud
11185 | * **[Cloudflare](https://github.com/cloudflare/mcp-server-cloudflare)** - Deploy and manage resources on the Cloudflare developer platform
11186 | * **[E2B](https://github.com/e2b-dev/mcp-server)** - Execute code in secure cloud sandboxes
11187 | * **[Neon](https://github.com/neondatabase/mcp-server-neon)** - Interact with the Neon serverless Postgres platform
11188 | * **[Obsidian Markdown Notes](https://github.com/calclavia/mcp-obsidian)** - Read and search through Markdown notes in Obsidian vaults
11189 | * **[Qdrant](https://github.com/qdrant/mcp-server-qdrant/)** - Implement semantic memory using the Qdrant vector search engine
11190 | * **[Raygun](https://github.com/MindscapeHQ/mcp-server-raygun)** - Access crash reporting and monitoring data
11191 | * **[Search1API](https://github.com/fatwang2/search1api-mcp)** - Unified API for search, crawling, and sitemaps
11192 | * **[Stripe](https://github.com/stripe/agent-toolkit)** - Interact with the Stripe API
11193 | * **[Tinybird](https://github.com/tinybirdco/mcp-tinybird)** - Interface with the Tinybird serverless ClickHouse platform
11194 | * **[Weaviate](https://github.com/weaviate/mcp-server-weaviate)** - Enable Agentic RAG through your Weaviate collection(s)
11195 | 
11196 | ## Community highlights
11197 | 
11198 | A growing ecosystem of community-developed servers extends MCP's capabilities:
11199 | 
11200 | * **[Docker](https://github.com/ckreiling/mcp-server-docker)** - Manage containers, images, volumes, and networks
11201 | * **[Kubernetes](https://github.com/Flux159/mcp-server-kubernetes)** - Manage pods, deployments, and services
11202 | * **[Linear](https://github.com/jerhadf/linear-mcp-server)** - Project management and issue tracking
11203 | * **[Snowflake](https://github.com/datawiz168/mcp-snowflake-service)** - Interact with Snowflake databases
11204 | * **[Spotify](https://github.com/varunneal/spotify-mcp)** - Control Spotify playback and manage playlists
11205 | * **[Todoist](https://github.com/abhiz123/todoist-mcp-server)** - Task management integration
11206 | 
11207 | > **Note:** Community servers are untested and should be used at your own risk. They are not affiliated with or endorsed by Anthropic.
11208 | 
11209 | For a complete list of community servers, visit the [MCP Servers Repository](https://github.com/modelcontextprotocol/servers).
11210 | 
11211 | ## Getting started
11212 | 
11213 | ### Using reference servers
11214 | 
11215 | TypeScript-based servers can be used directly with `npx`:
11216 | 
11217 | ```bash
11218 | npx -y @modelcontextprotocol/server-memory
11219 | ```
11220 | 
11221 | Python-based servers can be used with `uvx` (recommended) or `pip`:
11222 | 
11223 | ```bash
11224 | # Using uvx
11225 | uvx mcp-server-git
11226 | 
11227 | # Using pip
11228 | pip install mcp-server-git
11229 | python -m mcp_server_git
11230 | ```
11231 | 
11232 | ### Configuring with Claude
11233 | 
11234 | To use an MCP server with Claude, add it to your configuration:
11235 | 
11236 | ```json
11237 | {
11238 |   "mcpServers": {
11239 |     "memory": {
11240 |       "command": "npx",
11241 |       "args": ["-y", "@modelcontextprotocol/server-memory"]
11242 |     },
11243 |     "filesystem": {
11244 |       "command": "npx",
11245 |       "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"]
11246 |     },
11247 |     "github": {
11248 |       "command": "npx",
11249 |       "args": ["-y", "@modelcontextprotocol/server-github"],
11250 |       "env": {
11251 |         "GITHUB_PERSONAL_ACCESS_TOKEN": "<YOUR_TOKEN>"
11252 |       }
11253 |     }
11254 |   }
11255 | }
11256 | ```
11257 | 
11258 | ## Additional resources
11259 | 
11260 | * [MCP Servers Repository](https://github.com/modelcontextprotocol/servers) - Complete collection of reference implementations and community servers
11261 | * [Awesome MCP Servers](https://github.com/punkpeye/awesome-mcp-servers) - Curated list of MCP servers
11262 | * [MCP CLI](https://github.com/wong2/mcp-cli) - Command-line inspector for testing MCP servers
11263 | * [MCP Get](https://mcp-get.com) - Tool for installing and managing MCP servers
11264 | * [Supergateway](https://github.com/supercorp-ai/supergateway) - Run MCP stdio servers over SSE
11265 | 
11266 | Visit our [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions) to engage with the MCP community.
11267 | 
11268 | 
11269 | # Introduction
11270 | Source: https://modelcontextprotocol.io/introduction
11271 | 
11272 | Get started with the Model Context Protocol (MCP)
11273 | 
11274 | <Note>Java SDK released! Check out [what else is new.](/development/updates)</Note>
11275 | 
11276 | MCP is an open protocol that standardizes how applications provide context to LLMs. Think of MCP like a USB-C port for AI applications. Just as USB-C provides a standardized way to connect your devices to various peripherals and accessories, MCP provides a standardized way to connect AI models to different data sources and tools.
11277 | 
11278 | ## Why MCP?
11279 | 
11280 | MCP helps you build agents and complex workflows on top of LLMs. LLMs frequently need to integrate with data and tools, and MCP provides:
11281 | 
11282 | * A growing list of pre-built integrations that your LLM can directly plug into
11283 | * The flexibility to switch between LLM providers and vendors
11284 | * Best practices for securing your data within your infrastructure
11285 | 
11286 | ### General architecture
11287 | 
11288 | At its core, MCP follows a client-server architecture where a host application can connect to multiple servers:
11289 | 
11290 | ```mermaid
11291 | flowchart LR
11292 |     subgraph "Your Computer"
11293 |         Host["Host with MCP Client\n(Claude, IDEs, Tools)"]
11294 |         S1["MCP Server A"]
11295 |         S2["MCP Server B"]
11296 |         S3["MCP Server C"]
11297 |         Host <-->|"MCP Protocol"| S1
11298 |         Host <-->|"MCP Protocol"| S2
11299 |         Host <-->|"MCP Protocol"| S3
11300 |         S1 <--> D1[("Local\nData Source A")]
11301 |         S2 <--> D2[("Local\nData Source B")]
11302 |     end
11303 |     subgraph "Internet"
11304 |         S3 <-->|"Web APIs"| D3[("Remote\nService C")]
11305 |     end
11306 | ```
11307 | 
11308 | * **MCP Hosts**: Programs like Claude Desktop, IDEs, or AI tools that want to access data through MCP
11309 | * **MCP Clients**: Protocol clients that maintain 1:1 connections with servers
11310 | * **MCP Servers**: Lightweight programs that each expose specific capabilities through the standardized Model Context Protocol
11311 | * **Local Data Sources**: Your computer's files, databases, and services that MCP servers can securely access
11312 | * **Remote Services**: External systems available over the internet (e.g., through APIs) that MCP servers can connect to
11313 | 
11314 | ## Get started
11315 | 
11316 | Choose the path that best fits your needs:
11317 | 
11318 | #### Quick Starts
11319 | 
11320 | <CardGroup cols={2}>
11321 |   <Card title="For Server Developers" icon="bolt" href="/quickstart/server">
11322 |     Get started building your own server to use in Claude for Desktop and other clients
11323 |   </Card>
11324 | 
11325 |   <Card title="For Client Developers" icon="bolt" href="/quickstart/client">
11326 |     Get started building your own client that can integrate with all MCP servers
11327 |   </Card>
11328 | 
11329 |   <Card title="For Claude Desktop Users" icon="bolt" href="/quickstart/user">
11330 |     Get started using pre-built servers in Claude for Desktop
11331 |   </Card>
11332 | </CardGroup>
11333 | 
11334 | #### Examples
11335 | 
11336 | <CardGroup cols={2}>
11337 |   <Card title="Example Servers" icon="grid" href="/examples">
11338 |     Check out our gallery of official MCP servers and implementations
11339 |   </Card>
11340 | 
11341 |   <Card title="Example Clients" icon="cubes" href="/clients">
11342 |     View the list of clients that support MCP integrations
11343 |   </Card>
11344 | </CardGroup>
11345 | 
11346 | ## Tutorials
11347 | 
11348 | <CardGroup cols={2}>
11349 |   <Card title="Building MCP with LLMs" icon="comments" href="/tutorials/building-mcp-with-llms">
11350 |     Learn how to use LLMs like Claude to speed up your MCP development
11351 |   </Card>
11352 | 
11353 |   <Card title="Debugging Guide" icon="bug" href="/docs/tools/debugging">
11354 |     Learn how to effectively debug MCP servers and integrations
11355 |   </Card>
11356 | 
11357 |   <Card title="MCP Inspector" icon="magnifying-glass" href="/docs/tools/inspector">
11358 |     Test and inspect your MCP servers with our interactive debugging tool
11359 |   </Card>
11360 | 
11361 |   <Card title="MCP Workshop (Video, 2hr)" icon="person-chalkboard" href="https://www.youtube.com/watch?v=kQmXtrmQ5Zg">
11362 |     <iframe src="https://www.youtube.com/embed/kQmXtrmQ5Zg" />
11363 |   </Card>
11364 | </CardGroup>
11365 | 
11366 | ## Explore MCP
11367 | 
11368 | Dive deeper into MCP's core concepts and capabilities:
11369 | 
11370 | <CardGroup cols={2}>
11371 |   <Card title="Core architecture" icon="sitemap" href="/docs/concepts/architecture">
11372 |     Understand how MCP connects clients, servers, and LLMs
11373 |   </Card>
11374 | 
11375 |   <Card title="Resources" icon="database" href="/docs/concepts/resources">
11376 |     Expose data and content from your servers to LLMs
11377 |   </Card>
11378 | 
11379 |   <Card title="Prompts" icon="message" href="/docs/concepts/prompts">
11380 |     Create reusable prompt templates and workflows
11381 |   </Card>
11382 | 
11383 |   <Card title="Tools" icon="wrench" href="/docs/concepts/tools">
11384 |     Enable LLMs to perform actions through your server
11385 |   </Card>
11386 | 
11387 |   <Card title="Sampling" icon="robot" href="/docs/concepts/sampling">
11388 |     Let your servers request completions from LLMs
11389 |   </Card>
11390 | 
11391 |   <Card title="Transports" icon="network-wired" href="/docs/concepts/transports">
11392 |     Learn about MCP's communication mechanism
11393 |   </Card>
11394 | </CardGroup>
11395 | 
11396 | ## Contributing
11397 | 
11398 | Want to contribute? Check out our [Contributing Guide](/development/contributing) to learn how you can help improve MCP.
11399 | 
11400 | ## Support and Feedback
11401 | 
11402 | Here's how to get help or provide feedback:
11403 | 
11404 | * For bug reports and feature requests related to the MCP specification, SDKs, or documentation (open source), please [create a GitHub issue](https://github.com/modelcontextprotocol)
11405 | * For discussions or Q\&A about the MCP specification, use the [specification discussions](https://github.com/modelcontextprotocol/specification/discussions)
11406 | * For discussions or Q\&A about other MCP open source components, use the [organization discussions](https://github.com/orgs/modelcontextprotocol/discussions)
11407 | * For bug reports, feature requests, and questions related to Claude.app and claude.ai's MCP integration, please email [[email protected]](mailto:[email protected])
11408 | 
11409 | 
11410 | # For Client Developers
11411 | Source: https://modelcontextprotocol.io/quickstart/client
11412 | 
11413 | Get started building your own client that can integrate with all MCP servers.
11414 | 
11415 | In this tutorial, you'll learn how to build a LLM-powered chatbot client that connects to MCP servers. It helps to have gone through the [Server quickstart](/quickstart/server) that guides you through the basic of building your first server.
11416 | 
11417 | <Tabs>
11418 |   <Tab title="Python">
11419 |     [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-python)
11420 | 
11421 |     ## System Requirements
11422 | 
11423 |     Before starting, ensure your system meets these requirements:
11424 | 
11425 |     * Mac or Windows computer
11426 |     * Latest Python version installed
11427 |     * Latest version of `uv` installed
11428 | 
11429 |     ## Setting Up Your Environment
11430 | 
11431 |     First, create a new Python project with `uv`:
11432 | 
11433 |     ```bash
11434 |     # Create project directory
11435 |     uv init mcp-client
11436 |     cd mcp-client
11437 | 
11438 |     # Create virtual environment
11439 |     uv venv
11440 | 
11441 |     # Activate virtual environment
11442 |     # On Windows:
11443 |     .venv\Scripts\activate
11444 |     # On Unix or MacOS:
11445 |     source .venv/bin/activate
11446 | 
11447 |     # Install required packages
11448 |     uv add mcp anthropic python-dotenv
11449 | 
11450 |     # Remove boilerplate files
11451 |     rm hello.py
11452 | 
11453 |     # Create our main file
11454 |     touch client.py
11455 |     ```
11456 | 
11457 |     ## Setting Up Your API Key
11458 | 
11459 |     You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
11460 | 
11461 |     Create a `.env` file to store it:
11462 | 
11463 |     ```bash
11464 |     # Create .env file
11465 |     touch .env
11466 |     ```
11467 | 
11468 |     Add your key to the `.env` file:
11469 | 
11470 |     ```bash
11471 |     ANTHROPIC_API_KEY=<your key here>
11472 |     ```
11473 | 
11474 |     Add `.env` to your `.gitignore`:
11475 | 
11476 |     ```bash
11477 |     echo ".env" >> .gitignore
11478 |     ```
11479 | 
11480 |     <Warning>
11481 |       Make sure you keep your `ANTHROPIC_API_KEY` secure!
11482 |     </Warning>
11483 | 
11484 |     ## Creating the Client
11485 | 
11486 |     ### Basic Client Structure
11487 | 
11488 |     First, let's set up our imports and create the basic client class:
11489 | 
11490 |     ```python
11491 |     import asyncio
11492 |     from typing import Optional
11493 |     from contextlib import AsyncExitStack
11494 | 
11495 |     from mcp import ClientSession, StdioServerParameters
11496 |     from mcp.client.stdio import stdio_client
11497 | 
11498 |     from anthropic import Anthropic
11499 |     from dotenv import load_dotenv
11500 | 
11501 |     load_dotenv()  # load environment variables from .env
11502 | 
11503 |     class MCPClient:
11504 |         def __init__(self):
11505 |             # Initialize session and client objects
11506 |             self.session: Optional[ClientSession] = None
11507 |             self.exit_stack = AsyncExitStack()
11508 |             self.anthropic = Anthropic()
11509 |         # methods will go here
11510 |     ```
11511 | 
11512 |     ### Server Connection Management
11513 | 
11514 |     Next, we'll implement the method to connect to an MCP server:
11515 | 
11516 |     ```python
11517 |     async def connect_to_server(self, server_script_path: str):
11518 |         """Connect to an MCP server
11519 | 
11520 |         Args:
11521 |             server_script_path: Path to the server script (.py or .js)
11522 |         """
11523 |         is_python = server_script_path.endswith('.py')
11524 |         is_js = server_script_path.endswith('.js')
11525 |         if not (is_python or is_js):
11526 |             raise ValueError("Server script must be a .py or .js file")
11527 | 
11528 |         command = "python" if is_python else "node"
11529 |         server_params = StdioServerParameters(
11530 |             command=command,
11531 |             args=[server_script_path],
11532 |             env=None
11533 |         )
11534 | 
11535 |         stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
11536 |         self.stdio, self.write = stdio_transport
11537 |         self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))
11538 | 
11539 |         await self.session.initialize()
11540 | 
11541 |         # List available tools
11542 |         response = await self.session.list_tools()
11543 |         tools = response.tools
11544 |         print("\nConnected to server with tools:", [tool.name for tool in tools])
11545 |     ```
11546 | 
11547 |     ### Query Processing Logic
11548 | 
11549 |     Now let's add the core functionality for processing queries and handling tool calls:
11550 | 
11551 |     ```python
11552 |     async def process_query(self, query: str) -> str:
11553 |         """Process a query using Claude and available tools"""
11554 |         messages = [
11555 |             {
11556 |                 "role": "user",
11557 |                 "content": query
11558 |             }
11559 |         ]
11560 | 
11561 |         response = await self.session.list_tools()
11562 |         available_tools = [{
11563 |             "name": tool.name,
11564 |             "description": tool.description,
11565 |             "input_schema": tool.inputSchema
11566 |         } for tool in response.tools]
11567 | 
11568 |         # Initial Claude API call
11569 |         response = self.anthropic.messages.create(
11570 |             model="claude-3-5-sonnet-20241022",
11571 |             max_tokens=1000,
11572 |             messages=messages,
11573 |             tools=available_tools
11574 |         )
11575 | 
11576 |         # Process response and handle tool calls
11577 |         final_text = []
11578 | 
11579 |         assistant_message_content = []
11580 |         for content in response.content:
11581 |             if content.type == 'text':
11582 |                 final_text.append(content.text)
11583 |                 assistant_message_content.append(content)
11584 |             elif content.type == 'tool_use':
11585 |                 tool_name = content.name
11586 |                 tool_args = content.input
11587 | 
11588 |                 # Execute tool call
11589 |                 result = await self.session.call_tool(tool_name, tool_args)
11590 |                 final_text.append(f"[Calling tool {tool_name} with args {tool_args}]")
11591 | 
11592 |                 assistant_message_content.append(content)
11593 |                 messages.append({
11594 |                     "role": "assistant",
11595 |                     "content": assistant_message_content
11596 |                 })
11597 |                 messages.append({
11598 |                     "role": "user",
11599 |                     "content": [
11600 |                         {
11601 |                             "type": "tool_result",
11602 |                             "tool_use_id": content.id,
11603 |                             "content": result.content
11604 |                         }
11605 |                     ]
11606 |                 })
11607 | 
11608 |                 # Get next response from Claude
11609 |                 response = self.anthropic.messages.create(
11610 |                     model="claude-3-5-sonnet-20241022",
11611 |                     max_tokens=1000,
11612 |                     messages=messages,
11613 |                     tools=available_tools
11614 |                 )
11615 | 
11616 |                 final_text.append(response.content[0].text)
11617 | 
11618 |         return "\n".join(final_text)
11619 |     ```
11620 | 
11621 |     ### Interactive Chat Interface
11622 | 
11623 |     Now we'll add the chat loop and cleanup functionality:
11624 | 
11625 |     ```python
11626 |     async def chat_loop(self):
11627 |         """Run an interactive chat loop"""
11628 |         print("\nMCP Client Started!")
11629 |         print("Type your queries or 'quit' to exit.")
11630 | 
11631 |         while True:
11632 |             try:
11633 |                 query = input("\nQuery: ").strip()
11634 | 
11635 |                 if query.lower() == 'quit':
11636 |                     break
11637 | 
11638 |                 response = await self.process_query(query)
11639 |                 print("\n" + response)
11640 | 
11641 |             except Exception as e:
11642 |                 print(f"\nError: {str(e)}")
11643 | 
11644 |     async def cleanup(self):
11645 |         """Clean up resources"""
11646 |         await self.exit_stack.aclose()
11647 |     ```
11648 | 
11649 |     ### Main Entry Point
11650 | 
11651 |     Finally, we'll add the main execution logic:
11652 | 
11653 |     ```python
11654 |     async def main():
11655 |         if len(sys.argv) < 2:
11656 |             print("Usage: python client.py <path_to_server_script>")
11657 |             sys.exit(1)
11658 | 
11659 |         client = MCPClient()
11660 |         try:
11661 |             await client.connect_to_server(sys.argv[1])
11662 |             await client.chat_loop()
11663 |         finally:
11664 |             await client.cleanup()
11665 | 
11666 |     if __name__ == "__main__":
11667 |         import sys
11668 |         asyncio.run(main())
11669 |     ```
11670 | 
11671 |     You can find the complete `client.py` file [here.](https://gist.github.com/zckly/f3f28ea731e096e53b39b47bf0a2d4b1)
11672 | 
11673 |     ## Key Components Explained
11674 | 
11675 |     ### 1. Client Initialization
11676 | 
11677 |     * The `MCPClient` class initializes with session management and API clients
11678 |     * Uses `AsyncExitStack` for proper resource management
11679 |     * Configures the Anthropic client for Claude interactions
11680 | 
11681 |     ### 2. Server Connection
11682 | 
11683 |     * Supports both Python and Node.js servers
11684 |     * Validates server script type
11685 |     * Sets up proper communication channels
11686 |     * Initializes the session and lists available tools
11687 | 
11688 |     ### 3. Query Processing
11689 | 
11690 |     * Maintains conversation context
11691 |     * Handles Claude's responses and tool calls
11692 |     * Manages the message flow between Claude and tools
11693 |     * Combines results into a coherent response
11694 | 
11695 |     ### 4. Interactive Interface
11696 | 
11697 |     * Provides a simple command-line interface
11698 |     * Handles user input and displays responses
11699 |     * Includes basic error handling
11700 |     * Allows graceful exit
11701 | 
11702 |     ### 5. Resource Management
11703 | 
11704 |     * Proper cleanup of resources
11705 |     * Error handling for connection issues
11706 |     * Graceful shutdown procedures
11707 | 
11708 |     ## Common Customization Points
11709 | 
11710 |     1. **Tool Handling**
11711 |        * Modify `process_query()` to handle specific tool types
11712 |        * Add custom error handling for tool calls
11713 |        * Implement tool-specific response formatting
11714 | 
11715 |     2. **Response Processing**
11716 |        * Customize how tool results are formatted
11717 |        * Add response filtering or transformation
11718 |        * Implement custom logging
11719 | 
11720 |     3. **User Interface**
11721 |        * Add a GUI or web interface
11722 |        * Implement rich console output
11723 |        * Add command history or auto-completion
11724 | 
11725 |     ## Running the Client
11726 | 
11727 |     To run your client with any MCP server:
11728 | 
11729 |     ```bash
11730 |     uv run client.py path/to/server.py # python server
11731 |     uv run client.py path/to/build/index.js # node server
11732 |     ```
11733 | 
11734 |     <Note>
11735 |       If you're continuing the weather tutorial from the server quickstart, your command might look something like this: `python client.py .../weather/src/weather/server.py`
11736 |     </Note>
11737 | 
11738 |     The client will:
11739 | 
11740 |     1. Connect to the specified server
11741 |     2. List available tools
11742 |     3. Start an interactive chat session where you can:
11743 |        * Enter queries
11744 |        * See tool executions
11745 |        * Get responses from Claude
11746 | 
11747 |     Here's an example of what it should look like if connected to the weather server from the server quickstart:
11748 | 
11749 |     <Frame>
11750 |       <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/client-claude-cli-python.png" />
11751 |     </Frame>
11752 | 
11753 |     ## How It Works
11754 | 
11755 |     When you submit a query:
11756 | 
11757 |     1. The client gets the list of available tools from the server
11758 |     2. Your query is sent to Claude along with tool descriptions
11759 |     3. Claude decides which tools (if any) to use
11760 |     4. The client executes any requested tool calls through the server
11761 |     5. Results are sent back to Claude
11762 |     6. Claude provides a natural language response
11763 |     7. The response is displayed to you
11764 | 
11765 |     ## Best practices
11766 | 
11767 |     1. **Error Handling**
11768 |        * Always wrap tool calls in try-catch blocks
11769 |        * Provide meaningful error messages
11770 |        * Gracefully handle connection issues
11771 | 
11772 |     2. **Resource Management**
11773 |        * Use `AsyncExitStack` for proper cleanup
11774 |        * Close connections when done
11775 |        * Handle server disconnections
11776 | 
11777 |     3. **Security**
11778 |        * Store API keys securely in `.env`
11779 |        * Validate server responses
11780 |        * Be cautious with tool permissions
11781 | 
11782 |     ## Troubleshooting
11783 | 
11784 |     ### Server Path Issues
11785 | 
11786 |     * Double-check the path to your server script is correct
11787 |     * Use the absolute path if the relative path isn't working
11788 |     * For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
11789 |     * Verify the server file has the correct extension (.py for Python or .js for Node.js)
11790 | 
11791 |     Example of correct path usage:
11792 | 
11793 |     ```bash
11794 |     # Relative path
11795 |     uv run client.py ./server/weather.py
11796 | 
11797 |     # Absolute path
11798 |     uv run client.py /Users/username/projects/mcp-server/weather.py
11799 | 
11800 |     # Windows path (either format works)
11801 |     uv run client.py C:/projects/mcp-server/weather.py
11802 |     uv run client.py C:\\projects\\mcp-server\\weather.py
11803 |     ```
11804 | 
11805 |     ### Response Timing
11806 | 
11807 |     * The first response might take up to 30 seconds to return
11808 |     * This is normal and happens while:
11809 |       * The server initializes
11810 |       * Claude processes the query
11811 |       * Tools are being executed
11812 |     * Subsequent responses are typically faster
11813 |     * Don't interrupt the process during this initial waiting period
11814 | 
11815 |     ### Common Error Messages
11816 | 
11817 |     If you see:
11818 | 
11819 |     * `FileNotFoundError`: Check your server path
11820 |     * `Connection refused`: Ensure the server is running and the path is correct
11821 |     * `Tool execution failed`: Verify the tool's required environment variables are set
11822 |     * `Timeout error`: Consider increasing the timeout in your client configuration
11823 |   </Tab>
11824 | 
11825 |   <Tab title="Node">
11826 |     [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-typescript)
11827 | 
11828 |     ## System Requirements
11829 | 
11830 |     Before starting, ensure your system meets these requirements:
11831 | 
11832 |     * Mac or Windows computer
11833 |     * Node.js 16 or higher installed
11834 |     * Latest version of `npm` installed
11835 |     * Anthropic API key (Claude)
11836 | 
11837 |     ## Setting Up Your Environment
11838 | 
11839 |     First, let's create and set up our project:
11840 | 
11841 |     <CodeGroup>
11842 |       ```bash MacOS/Linux
11843 |       # Create project directory
11844 |       mkdir mcp-client-typescript
11845 |       cd mcp-client-typescript
11846 | 
11847 |       # Initialize npm project
11848 |       npm init -y
11849 | 
11850 |       # Install dependencies
11851 |       npm install @anthropic-ai/sdk @modelcontextprotocol/sdk dotenv
11852 | 
11853 |       # Install dev dependencies
11854 |       npm install -D @types/node typescript
11855 | 
11856 |       # Create source file
11857 |       touch index.ts
11858 |       ```
11859 | 
11860 |       ```powershell Windows
11861 |       # Create project directory
11862 |       md mcp-client-typescript
11863 |       cd mcp-client-typescript
11864 | 
11865 |       # Initialize npm project
11866 |       npm init -y
11867 | 
11868 |       # Install dependencies
11869 |       npm install @anthropic-ai/sdk @modelcontextprotocol/sdk dotenv
11870 | 
11871 |       # Install dev dependencies
11872 |       npm install -D @types/node typescript
11873 | 
11874 |       # Create source file
11875 |       new-item index.ts
11876 |       ```
11877 |     </CodeGroup>
11878 | 
11879 |     Update your `package.json` to set `type: "module"` and a build script:
11880 | 
11881 |     ```json package.json
11882 |     {
11883 |       "type": "module",
11884 |       "scripts": {
11885 |         "build": "tsc && chmod 755 build/index.js"
11886 |       }
11887 |     }
11888 |     ```
11889 | 
11890 |     Create a `tsconfig.json` in the root of your project:
11891 | 
11892 |     ```json tsconfig.json
11893 |     {
11894 |       "compilerOptions": {
11895 |         "target": "ES2022",
11896 |         "module": "Node16",
11897 |         "moduleResolution": "Node16",
11898 |         "outDir": "./build",
11899 |         "rootDir": "./",
11900 |         "strict": true,
11901 |         "esModuleInterop": true,
11902 |         "skipLibCheck": true,
11903 |         "forceConsistentCasingInFileNames": true
11904 |       },
11905 |       "include": ["index.ts"],
11906 |       "exclude": ["node_modules"]
11907 |     }
11908 |     ```
11909 | 
11910 |     ## Setting Up Your API Key
11911 | 
11912 |     You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
11913 | 
11914 |     Create a `.env` file to store it:
11915 | 
11916 |     ```bash
11917 |     echo "ANTHROPIC_API_KEY=<your key here>" > .env
11918 |     ```
11919 | 
11920 |     Add `.env` to your `.gitignore`:
11921 | 
11922 |     ```bash
11923 |     echo ".env" >> .gitignore
11924 |     ```
11925 | 
11926 |     <Warning>
11927 |       Make sure you keep your `ANTHROPIC_API_KEY` secure!
11928 |     </Warning>
11929 | 
11930 |     ## Creating the Client
11931 | 
11932 |     ### Basic Client Structure
11933 | 
11934 |     First, let's set up our imports and create the basic client class in `index.ts`:
11935 | 
11936 |     ```typescript
11937 |     import { Anthropic } from "@anthropic-ai/sdk";
11938 |     import {
11939 |       MessageParam,
11940 |       Tool,
11941 |     } from "@anthropic-ai/sdk/resources/messages/messages.mjs";
11942 |     import { Client } from "@modelcontextprotocol/sdk/client/index.js";
11943 |     import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
11944 |     import readline from "readline/promises";
11945 |     import dotenv from "dotenv";
11946 | 
11947 |     dotenv.config();
11948 | 
11949 |     const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
11950 |     if (!ANTHROPIC_API_KEY) {
11951 |       throw new Error("ANTHROPIC_API_KEY is not set");
11952 |     }
11953 | 
11954 |     class MCPClient {
11955 |       private mcp: Client;
11956 |       private anthropic: Anthropic;
11957 |       private transport: StdioClientTransport | null = null;
11958 |       private tools: Tool[] = [];
11959 | 
11960 |       constructor() {
11961 |         this.anthropic = new Anthropic({
11962 |           apiKey: ANTHROPIC_API_KEY,
11963 |         });
11964 |         this.mcp = new Client({ name: "mcp-client-cli", version: "1.0.0" });
11965 |       }
11966 |       // methods will go here
11967 |     }
11968 |     ```
11969 | 
11970 |     ### Server Connection Management
11971 | 
11972 |     Next, we'll implement the method to connect to an MCP server:
11973 | 
11974 |     ```typescript
11975 |     async connectToServer(serverScriptPath: string) {
11976 |       try {
11977 |         const isJs = serverScriptPath.endsWith(".js");
11978 |         const isPy = serverScriptPath.endsWith(".py");
11979 |         if (!isJs && !isPy) {
11980 |           throw new Error("Server script must be a .js or .py file");
11981 |         }
11982 |         const command = isPy
11983 |           ? process.platform === "win32"
11984 |             ? "python"
11985 |             : "python3"
11986 |           : process.execPath;
11987 |         
11988 |         this.transport = new StdioClientTransport({
11989 |           command,
11990 |           args: [serverScriptPath],
11991 |         });
11992 |         this.mcp.connect(this.transport);
11993 |         
11994 |         const toolsResult = await this.mcp.listTools();
11995 |         this.tools = toolsResult.tools.map((tool) => {
11996 |           return {
11997 |             name: tool.name,
11998 |             description: tool.description,
11999 |             input_schema: tool.inputSchema,
12000 |           };
12001 |         });
12002 |         console.log(
12003 |           "Connected to server with tools:",
12004 |           this.tools.map(({ name }) => name)
12005 |         );
12006 |       } catch (e) {
12007 |         console.log("Failed to connect to MCP server: ", e);
12008 |         throw e;
12009 |       }
12010 |     }
12011 |     ```
12012 | 
12013 |     ### Query Processing Logic
12014 | 
12015 |     Now let's add the core functionality for processing queries and handling tool calls:
12016 | 
12017 |     ```typescript
12018 |     async processQuery(query: string) {
12019 |       const messages: MessageParam[] = [
12020 |         {
12021 |           role: "user",
12022 |           content: query,
12023 |         },
12024 |       ];
12025 | 
12026 |       const response = await this.anthropic.messages.create({
12027 |         model: "claude-3-5-sonnet-20241022",
12028 |         max_tokens: 1000,
12029 |         messages,
12030 |         tools: this.tools,
12031 |       });
12032 | 
12033 |       const finalText = [];
12034 |       const toolResults = [];
12035 | 
12036 |       for (const content of response.content) {
12037 |         if (content.type === "text") {
12038 |           finalText.push(content.text);
12039 |         } else if (content.type === "tool_use") {
12040 |           const toolName = content.name;
12041 |           const toolArgs = content.input as { [x: string]: unknown } | undefined;
12042 | 
12043 |           const result = await this.mcp.callTool({
12044 |             name: toolName,
12045 |             arguments: toolArgs,
12046 |           });
12047 |           toolResults.push(result);
12048 |           finalText.push(
12049 |             `[Calling tool ${toolName} with args ${JSON.stringify(toolArgs)}]`
12050 |           );
12051 | 
12052 |           messages.push({
12053 |             role: "user",
12054 |             content: result.content as string,
12055 |           });
12056 | 
12057 |           const response = await this.anthropic.messages.create({
12058 |             model: "claude-3-5-sonnet-20241022",
12059 |             max_tokens: 1000,
12060 |             messages,
12061 |           });
12062 | 
12063 |           finalText.push(
12064 |             response.content[0].type === "text" ? response.content[0].text : ""
12065 |           );
12066 |         }
12067 |       }
12068 | 
12069 |       return finalText.join("\n");
12070 |     }
12071 |     ```
12072 | 
12073 |     ### Interactive Chat Interface
12074 | 
12075 |     Now we'll add the chat loop and cleanup functionality:
12076 | 
12077 |     ```typescript
12078 |     async chatLoop() {
12079 |       const rl = readline.createInterface({
12080 |         input: process.stdin,
12081 |         output: process.stdout,
12082 |       });
12083 | 
12084 |       try {
12085 |         console.log("\nMCP Client Started!");
12086 |         console.log("Type your queries or 'quit' to exit.");
12087 | 
12088 |         while (true) {
12089 |           const message = await rl.question("\nQuery: ");
12090 |           if (message.toLowerCase() === "quit") {
12091 |             break;
12092 |           }
12093 |           const response = await this.processQuery(message);
12094 |           console.log("\n" + response);
12095 |         }
12096 |       } finally {
12097 |         rl.close();
12098 |       }
12099 |     }
12100 | 
12101 |     async cleanup() {
12102 |       await this.mcp.close();
12103 |     }
12104 |     ```
12105 | 
12106 |     ### Main Entry Point
12107 | 
12108 |     Finally, we'll add the main execution logic:
12109 | 
12110 |     ```typescript
12111 |     async function main() {
12112 |       if (process.argv.length < 3) {
12113 |         console.log("Usage: node index.ts <path_to_server_script>");
12114 |         return;
12115 |       }
12116 |       const mcpClient = new MCPClient();
12117 |       try {
12118 |         await mcpClient.connectToServer(process.argv[2]);
12119 |         await mcpClient.chatLoop();
12120 |       } finally {
12121 |         await mcpClient.cleanup();
12122 |         process.exit(0);
12123 |       }
12124 |     }
12125 | 
12126 |     main();
12127 |     ```
12128 | 
12129 |     ## Running the Client
12130 | 
12131 |     To run your client with any MCP server:
12132 | 
12133 |     ```bash
12134 |     # Build TypeScript
12135 |     npm run build
12136 | 
12137 |     # Run the client
12138 |     node build/index.js path/to/server.py # python server
12139 |     node build/index.js path/to/build/index.js # node server
12140 |     ```
12141 | 
12142 |     <Note>
12143 |       If you're continuing the weather tutorial from the server quickstart, your command might look something like this: `node build/index.js .../quickstart-resources/weather-server-typescript/build/index.js`
12144 |     </Note>
12145 | 
12146 |     **The client will:**
12147 | 
12148 |     1. Connect to the specified server
12149 |     2. List available tools
12150 |     3. Start an interactive chat session where you can:
12151 |        * Enter queries
12152 |        * See tool executions
12153 |        * Get responses from Claude
12154 | 
12155 |     ## How It Works
12156 | 
12157 |     When you submit a query:
12158 | 
12159 |     1. The client gets the list of available tools from the server
12160 |     2. Your query is sent to Claude along with tool descriptions
12161 |     3. Claude decides which tools (if any) to use
12162 |     4. The client executes any requested tool calls through the server
12163 |     5. Results are sent back to Claude
12164 |     6. Claude provides a natural language response
12165 |     7. The response is displayed to you
12166 | 
12167 |     ## Best practices
12168 | 
12169 |     1. **Error Handling**
12170 |        * Use TypeScript's type system for better error detection
12171 |        * Wrap tool calls in try-catch blocks
12172 |        * Provide meaningful error messages
12173 |        * Gracefully handle connection issues
12174 | 
12175 |     2. **Security**
12176 |        * Store API keys securely in `.env`
12177 |        * Validate server responses
12178 |        * Be cautious with tool permissions
12179 | 
12180 |     ## Troubleshooting
12181 | 
12182 |     ### Server Path Issues
12183 | 
12184 |     * Double-check the path to your server script is correct
12185 |     * Use the absolute path if the relative path isn't working
12186 |     * For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
12187 |     * Verify the server file has the correct extension (.js for Node.js or .py for Python)
12188 | 
12189 |     Example of correct path usage:
12190 | 
12191 |     ```bash
12192 |     # Relative path
12193 |     node build/index.js ./server/build/index.js
12194 | 
12195 |     # Absolute path
12196 |     node build/index.js /Users/username/projects/mcp-server/build/index.js
12197 | 
12198 |     # Windows path (either format works)
12199 |     node build/index.js C:/projects/mcp-server/build/index.js
12200 |     node build/index.js C:\\projects\\mcp-server\\build\\index.js
12201 |     ```
12202 | 
12203 |     ### Response Timing
12204 | 
12205 |     * The first response might take up to 30 seconds to return
12206 |     * This is normal and happens while:
12207 |       * The server initializes
12208 |       * Claude processes the query
12209 |       * Tools are being executed
12210 |     * Subsequent responses are typically faster
12211 |     * Don't interrupt the process during this initial waiting period
12212 | 
12213 |     ### Common Error Messages
12214 | 
12215 |     If you see:
12216 | 
12217 |     * `Error: Cannot find module`: Check your build folder and ensure TypeScript compilation succeeded
12218 |     * `Connection refused`: Ensure the server is running and the path is correct
12219 |     * `Tool execution failed`: Verify the tool's required environment variables are set
12220 |     * `ANTHROPIC_API_KEY is not set`: Check your .env file and environment variables
12221 |     * `TypeError`: Ensure you're using the correct types for tool arguments
12222 |   </Tab>
12223 | 
12224 |   <Tab title="Java">
12225 |     <Note>
12226 |       This is a quickstart demo based on Spring AI MCP auto-configuration and boot starters.
12227 |       To learn how to create sync and async MCP Clients manually, consult the [Java SDK Client](/sdk/java/mcp-client) documentation
12228 |     </Note>
12229 | 
12230 |     This example demonstrates how to build an interactive chatbot that combines Spring AI's Model Context Protocol (MCP) with the [Brave Search MCP Server](https://github.com/modelcontextprotocol/servers/tree/main/src/brave-search). The application creates a conversational interface powered by Anthropic's Claude AI model that can perform internet searches through Brave Search, enabling natural language interactions with real-time web data.
12231 |     [You can find the complete code for this tutorial here.](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/web-search/brave-chatbot)
12232 | 
12233 |     ## System Requirements
12234 | 
12235 |     Before starting, ensure your system meets these requirements:
12236 | 
12237 |     * Java 17 or higher
12238 |     * Maven 3.6+
12239 |     * npx package manager
12240 |     * Anthropic API key (Claude)
12241 |     * Brave Search API key
12242 | 
12243 |     ## Setting Up Your Environment
12244 | 
12245 |     1. Install npx (Node Package eXecute):
12246 |        First, make sure to install [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)
12247 |        and then run:
12248 |        ```bash
12249 |        npm install -g npx
12250 |        ```
12251 | 
12252 |     2. Clone the repository:
12253 |        ```bash
12254 |        git clone https://github.com/spring-projects/spring-ai-examples.git
12255 |        cd model-context-protocol/brave-chatbot
12256 |        ```
12257 | 
12258 |     3. Set up your API keys:
12259 |        ```bash
12260 |        export ANTHROPIC_API_KEY='your-anthropic-api-key-here'
12261 |        export BRAVE_API_KEY='your-brave-api-key-here'
12262 |        ```
12263 | 
12264 |     4. Build the application:
12265 |        ```bash
12266 |        ./mvnw clean install
12267 |        ```
12268 | 
12269 |     5. Run the application using Maven:
12270 |        ```bash
12271 |        ./mvnw spring-boot:run
12272 |        ```
12273 | 
12274 |     <Warning>
12275 |       Make sure you keep your `ANTHROPIC_API_KEY` and `BRAVE_API_KEY` keys secure!
12276 |     </Warning>
12277 | 
12278 |     ## How it Works
12279 | 
12280 |     The application integrates Spring AI with the Brave Search MCP server through several components:
12281 | 
12282 |     ### MCP Client Configuration
12283 | 
12284 |     1. Required dependencies in pom.xml:
12285 | 
12286 |     ```xml
12287 |     <dependency>
12288 |         <groupId>org.springframework.ai</groupId>
12289 |         <artifactId>spring-ai-mcp-client-spring-boot-starter</artifactId>
12290 |     </dependency>
12291 |     <dependency>
12292 |         <groupId>org.springframework.ai</groupId>
12293 |         <artifactId>spring-ai-anthropic-spring-boot-starter</artifactId>
12294 |     </dependency>
12295 |     ```
12296 | 
12297 |     2. Application properties (application.yml):
12298 | 
12299 |     ```yml
12300 |     spring:
12301 |       ai:
12302 |         mcp:
12303 |           client:
12304 |             enabled: true
12305 |             name: brave-search-client
12306 |             version: 1.0.0
12307 |             type: SYNC
12308 |             request-timeout: 20s
12309 |             stdio:
12310 |               root-change-notification: true
12311 |               servers-configuration: classpath:/mcp-servers-config.json
12312 |         anthropic:
12313 |           api-key: ${ANTHROPIC_API_KEY}
12314 |     ```
12315 | 
12316 |     This activates the `spring-ai-mcp-client-spring-boot-starter` to create one or more `McpClient`s based on the provided server configuration.
12317 | 
12318 |     3. MCP Server Configuration (`mcp-servers-config.json`):
12319 | 
12320 |     ```json
12321 |     {
12322 |       "mcpServers": {
12323 |         "brave-search": {
12324 |           "command": "npx",
12325 |           "args": [
12326 |             "-y",
12327 |             "@modelcontextprotocol/server-brave-search"
12328 |           ],
12329 |           "env": {
12330 |             "BRAVE_API_KEY": "<PUT YOUR BRAVE API KEY>"
12331 |           }
12332 |         }
12333 |       }
12334 |     }
12335 |     ```
12336 | 
12337 |     ### Chat Implementation
12338 | 
12339 |     The chatbot is implemented using Spring AI's ChatClient with MCP tool integration:
12340 | 
12341 |     ```java
12342 |     var chatClient = chatClientBuilder
12343 |         .defaultSystem("You are useful assistant, expert in AI and Java.")
12344 |         .defaultTools((Object[]) mcpToolAdapter.toolCallbacks())
12345 |         .defaultAdvisors(new MessageChatMemoryAdvisor(new InMemoryChatMemory()))
12346 |         .build();
12347 |     ```
12348 | 
12349 |     Key features:
12350 | 
12351 |     * Uses Claude AI model for natural language understanding
12352 |     * Integrates Brave Search through MCP for real-time web search capabilities
12353 |     * Maintains conversation memory using InMemoryChatMemory
12354 |     * Runs as an interactive command-line application
12355 | 
12356 |     ### Build and run
12357 | 
12358 |     ```bash
12359 |     ./mvnw clean install
12360 |     java -jar ./target/ai-mcp-brave-chatbot-0.0.1-SNAPSHOT.jar
12361 |     ```
12362 | 
12363 |     or
12364 | 
12365 |     ```bash
12366 |     ./mvnw spring-boot:run
12367 |     ```
12368 | 
12369 |     The application will start an interactive chat session where you can ask questions. The chatbot will use Brave Search when it needs to find information from the internet to answer your queries.
12370 | 
12371 |     The chatbot can:
12372 | 
12373 |     * Answer questions using its built-in knowledge
12374 |     * Perform web searches when needed using Brave Search
12375 |     * Remember context from previous messages in the conversation
12376 |     * Combine information from multiple sources to provide comprehensive answers
12377 | 
12378 |     ### Advanced Configuration
12379 | 
12380 |     The MCP client supports additional configuration options:
12381 | 
12382 |     * Client customization through `McpSyncClientCustomizer` or `McpAsyncClientCustomizer`
12383 |     * Multiple clients with multiple transport types: `STDIO` and `SSE` (Server-Sent Events)
12384 |     * Integration with Spring AI's tool execution framework
12385 |     * Automatic client initialization and lifecycle management
12386 | 
12387 |     For WebFlux-based applications, you can use the WebFlux starter instead:
12388 | 
12389 |     ```xml
12390 |     <dependency>
12391 |         <groupId>org.springframework.ai</groupId>
12392 |         <artifactId>spring-ai-mcp-client-webflux-spring-boot-starter</artifactId>
12393 |     </dependency>
12394 |     ```
12395 | 
12396 |     This provides similar functionality but uses a WebFlux-based SSE transport implementation, recommended for production deployments.
12397 |   </Tab>
12398 | </Tabs>
12399 | 
12400 | ## Next steps
12401 | 
12402 | <CardGroup cols={2}>
12403 |   <Card title="Example servers" icon="grid" href="/examples">
12404 |     Check out our gallery of official MCP servers and implementations
12405 |   </Card>
12406 | 
12407 |   <Card title="Clients" icon="cubes" href="/clients">
12408 |     View the list of clients that support MCP integrations
12409 |   </Card>
12410 | 
12411 |   <Card title="Building MCP with LLMs" icon="comments" href="/tutorials/building-mcp-with-llms">
12412 |     Learn how to use LLMs like Claude to speed up your MCP development
12413 |   </Card>
12414 | 
12415 |   <Card title="Core architecture" icon="sitemap" href="/docs/concepts/architecture">
12416 |     Understand how MCP connects clients, servers, and LLMs
12417 |   </Card>
12418 | </CardGroup>
12419 | 
12420 | 
12421 | # For Server Developers
12422 | Source: https://modelcontextprotocol.io/quickstart/server
12423 | 
12424 | Get started building your own server to use in Claude for Desktop and other clients.
12425 | 
12426 | In this tutorial, we'll build a simple MCP weather server and connect it to a host, Claude for Desktop. We'll start with a basic setup, and then progress to more complex use cases.
12427 | 
12428 | ### What we'll be building
12429 | 
12430 | Many LLMs (including Claude) do not currently have the ability to fetch the forecast and severe weather alerts. Let's use MCP to solve that!
12431 | 
12432 | We'll build a server that exposes two tools: `get-alerts` and `get-forecast`. Then we'll connect the server to an MCP host (in this case, Claude for Desktop):
12433 | 
12434 | <Frame>
12435 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/weather-alerts.png" />
12436 | </Frame>
12437 | 
12438 | <Frame>
12439 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/current-weather.png" />
12440 | </Frame>
12441 | 
12442 | <Note>
12443 |   Servers can connect to any client. We've chosen Claude for Desktop here for simplicity, but we also have guides on [building your own client](/quickstart/client) as well as a [list of other clients here](/clients).
12444 | </Note>
12445 | 
12446 | <Accordion title="Why Claude for Desktop and not Claude.ai?">
12447 |   Because servers are locally run, MCP currently only supports desktop hosts. Remote hosts are in active development.
12448 | </Accordion>
12449 | 
12450 | ### Core MCP Concepts
12451 | 
12452 | MCP servers can provide three main types of capabilities:
12453 | 
12454 | 1. **Resources**: File-like data that can be read by clients (like API responses or file contents)
12455 | 2. **Tools**: Functions that can be called by the LLM (with user approval)
12456 | 3. **Prompts**: Pre-written templates that help users accomplish specific tasks
12457 | 
12458 | This tutorial will primarily focus on tools.
12459 | 
12460 | <Tabs>
12461 |   <Tab title="Python">
12462 |     Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-python)
12463 | 
12464 |     ### Prerequisite knowledge
12465 | 
12466 |     This quickstart assumes you have familiarity with:
12467 | 
12468 |     * Python
12469 |     * LLMs like Claude
12470 | 
12471 |     ### System requirements
12472 | 
12473 |     * Python 3.10 or higher installed.
12474 |     * You must use the Python MCP SDK 1.2.0 or higher.
12475 | 
12476 |     ### Set up your environment
12477 | 
12478 |     First, let's install `uv` and set up our Python project and environment:
12479 | 
12480 |     <CodeGroup>
12481 |       ```bash MacOS/Linux
12482 |       curl -LsSf https://astral.sh/uv/install.sh | sh
12483 |       ```
12484 | 
12485 |       ```powershell Windows
12486 |       powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
12487 |       ```
12488 |     </CodeGroup>
12489 | 
12490 |     Make sure to restart your terminal afterwards to ensure that the `uv` command gets picked up.
12491 | 
12492 |     Now, let's create and set up our project:
12493 | 
12494 |     <CodeGroup>
12495 |       ```bash MacOS/Linux
12496 |       # Create a new directory for our project
12497 |       uv init weather
12498 |       cd weather
12499 | 
12500 |       # Create virtual environment and activate it
12501 |       uv venv
12502 |       source .venv/bin/activate
12503 | 
12504 |       # Install dependencies
12505 |       uv add "mcp[cli]" httpx
12506 | 
12507 |       # Create our server file
12508 |       touch weather.py
12509 |       ```
12510 | 
12511 |       ```powershell Windows
12512 |       # Create a new directory for our project
12513 |       uv init weather
12514 |       cd weather
12515 | 
12516 |       # Create virtual environment and activate it
12517 |       uv venv
12518 |       .venv\Scripts\activate
12519 | 
12520 |       # Install dependencies
12521 |       uv add mcp[cli] httpx
12522 | 
12523 |       # Create our server file
12524 |       new-item weather.py
12525 |       ```
12526 |     </CodeGroup>
12527 | 
12528 |     Now let's dive into building your server.
12529 | 
12530 |     ## Building your server
12531 | 
12532 |     ### Importing packages and setting up the instance
12533 | 
12534 |     Add these to the top of your `weather.py`:
12535 | 
12536 |     ```python
12537 |     from typing import Any
12538 |     import httpx
12539 |     from mcp.server.fastmcp import FastMCP
12540 | 
12541 |     # Initialize FastMCP server
12542 |     mcp = FastMCP("weather")
12543 | 
12544 |     # Constants
12545 |     NWS_API_BASE = "https://api.weather.gov"
12546 |     USER_AGENT = "weather-app/1.0"
12547 |     ```
12548 | 
12549 |     The FastMCP class uses Python type hints and docstrings to automatically generate tool definitions, making it easy to create and maintain MCP tools.
12550 | 
12551 |     ### Helper functions
12552 | 
12553 |     Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
12554 | 
12555 |     ```python
12556 |     async def make_nws_request(url: str) -> dict[str, Any] | None:
12557 |         """Make a request to the NWS API with proper error handling."""
12558 |         headers = {
12559 |             "User-Agent": USER_AGENT,
12560 |             "Accept": "application/geo+json"
12561 |         }
12562 |         async with httpx.AsyncClient() as client:
12563 |             try:
12564 |                 response = await client.get(url, headers=headers, timeout=30.0)
12565 |                 response.raise_for_status()
12566 |                 return response.json()
12567 |             except Exception:
12568 |                 return None
12569 | 
12570 |     def format_alert(feature: dict) -> str:
12571 |         """Format an alert feature into a readable string."""
12572 |         props = feature["properties"]
12573 |         return f"""
12574 |     Event: {props.get('event', 'Unknown')}
12575 |     Area: {props.get('areaDesc', 'Unknown')}
12576 |     Severity: {props.get('severity', 'Unknown')}
12577 |     Description: {props.get('description', 'No description available')}
12578 |     Instructions: {props.get('instruction', 'No specific instructions provided')}
12579 |     """
12580 |     ```
12581 | 
12582 |     ### Implementing tool execution
12583 | 
12584 |     The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
12585 | 
12586 |     ```python
12587 |     @mcp.tool()
12588 |     async def get_alerts(state: str) -> str:
12589 |         """Get weather alerts for a US state.
12590 | 
12591 |         Args:
12592 |             state: Two-letter US state code (e.g. CA, NY)
12593 |         """
12594 |         url = f"{NWS_API_BASE}/alerts/active/area/{state}"
12595 |         data = await make_nws_request(url)
12596 | 
12597 |         if not data or "features" not in data:
12598 |             return "Unable to fetch alerts or no alerts found."
12599 | 
12600 |         if not data["features"]:
12601 |             return "No active alerts for this state."
12602 | 
12603 |         alerts = [format_alert(feature) for feature in data["features"]]
12604 |         return "\n---\n".join(alerts)
12605 | 
12606 |     @mcp.tool()
12607 |     async def get_forecast(latitude: float, longitude: float) -> str:
12608 |         """Get weather forecast for a location.
12609 | 
12610 |         Args:
12611 |             latitude: Latitude of the location
12612 |             longitude: Longitude of the location
12613 |         """
12614 |         # First get the forecast grid endpoint
12615 |         points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
12616 |         points_data = await make_nws_request(points_url)
12617 | 
12618 |         if not points_data:
12619 |             return "Unable to fetch forecast data for this location."
12620 | 
12621 |         # Get the forecast URL from the points response
12622 |         forecast_url = points_data["properties"]["forecast"]
12623 |         forecast_data = await make_nws_request(forecast_url)
12624 | 
12625 |         if not forecast_data:
12626 |             return "Unable to fetch detailed forecast."
12627 | 
12628 |         # Format the periods into a readable forecast
12629 |         periods = forecast_data["properties"]["periods"]
12630 |         forecasts = []
12631 |         for period in periods[:5]:  # Only show next 5 periods
12632 |             forecast = f"""
12633 |     {period['name']}:
12634 |     Temperature: {period['temperature']}°{period['temperatureUnit']}
12635 |     Wind: {period['windSpeed']} {period['windDirection']}
12636 |     Forecast: {period['detailedForecast']}
12637 |     """
12638 |             forecasts.append(forecast)
12639 | 
12640 |         return "\n---\n".join(forecasts)
12641 |     ```
12642 | 
12643 |     ### Running the server
12644 | 
12645 |     Finally, let's initialize and run the server:
12646 | 
12647 |     ```python
12648 |     if __name__ == "__main__":
12649 |         # Initialize and run the server
12650 |         mcp.run(transport='stdio')
12651 |     ```
12652 | 
12653 |     Your server is complete! Run `uv run weather.py` to confirm that everything's working.
12654 | 
12655 |     Let's now test your server from an existing MCP host, Claude for Desktop.
12656 | 
12657 |     ## Testing your server with Claude for Desktop
12658 | 
12659 |     <Note>
12660 |       Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/quickstart/client) tutorial to build an MCP client that connects to the server we just built.
12661 |     </Note>
12662 | 
12663 |     First, make sure you have Claude for Desktop installed. [You can install the latest version
12664 |     here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
12665 | 
12666 |     We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
12667 | 
12668 |     For example, if you have [VS Code](https://code.visualstudio.com/) installed:
12669 | 
12670 |     <Tabs>
12671 |       <Tab title="MacOS/Linux">
12672 |         ```bash
12673 |         code ~/Library/Application\ Support/Claude/claude_desktop_config.json
12674 |         ```
12675 |       </Tab>
12676 | 
12677 |       <Tab title="Windows">
12678 |         ```powershell
12679 |         code $env:AppData\Claude\claude_desktop_config.json
12680 |         ```
12681 |       </Tab>
12682 |     </Tabs>
12683 | 
12684 |     You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
12685 | 
12686 |     In this case, we'll add our single weather server like so:
12687 | 
12688 |     <Tabs>
12689 |       <Tab title="MacOS/Linux">
12690 |         ```json Python
12691 |         {
12692 |             "mcpServers": {
12693 |                 "weather": {
12694 |                     "command": "uv",
12695 |                     "args": [
12696 |                         "--directory",
12697 |                         "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
12698 |                         "run",
12699 |                         "weather.py"
12700 |                     ]
12701 |                 }
12702 |             }
12703 |         }
12704 |         ```
12705 |       </Tab>
12706 | 
12707 |       <Tab title="Windows">
12708 |         ```json Python
12709 |         {
12710 |             "mcpServers": {
12711 |                 "weather": {
12712 |                     "command": "uv",
12713 |                     "args": [
12714 |                         "--directory",
12715 |                         "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather",
12716 |                         "run",
12717 |                         "weather.py"
12718 |                     ]
12719 |                 }
12720 |             }
12721 |         }
12722 |         ```
12723 |       </Tab>
12724 |     </Tabs>
12725 | 
12726 |     <Warning>
12727 |       You may need to put the full path to the `uv` executable in the `command` field. You can get this by running `which uv` on MacOS/Linux or `where uv` on Windows.
12728 |     </Warning>
12729 | 
12730 |     <Note>
12731 |       Make sure you pass in the absolute path to your server.
12732 |     </Note>
12733 | 
12734 |     This tells Claude for Desktop:
12735 | 
12736 |     1. There's an MCP server named "weather"
12737 |     2. To launch it by running `uv --directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather run weather.py`
12738 | 
12739 |     Save the file, and restart **Claude for Desktop**.
12740 |   </Tab>
12741 | 
12742 |   <Tab title="Node">
12743 |     Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-typescript)
12744 | 
12745 |     ### Prerequisite knowledge
12746 | 
12747 |     This quickstart assumes you have familiarity with:
12748 | 
12749 |     * TypeScript
12750 |     * LLMs like Claude
12751 | 
12752 |     ### System requirements
12753 | 
12754 |     For TypeScript, make sure you have the latest version of Node installed.
12755 | 
12756 |     ### Set up your environment
12757 | 
12758 |     First, let's install Node.js and npm if you haven't already. You can download them from [nodejs.org](https://nodejs.org/).
12759 |     Verify your Node.js installation:
12760 | 
12761 |     ```bash
12762 |     node --version
12763 |     npm --version
12764 |     ```
12765 | 
12766 |     For this tutorial, you'll need Node.js version 16 or higher.
12767 | 
12768 |     Now, let's create and set up our project:
12769 | 
12770 |     <CodeGroup>
12771 |       ```bash MacOS/Linux
12772 |       # Create a new directory for our project
12773 |       mkdir weather
12774 |       cd weather
12775 | 
12776 |       # Initialize a new npm project
12777 |       npm init -y
12778 | 
12779 |       # Install dependencies
12780 |       npm install @modelcontextprotocol/sdk zod
12781 |       npm install -D @types/node typescript
12782 | 
12783 |       # Create our files
12784 |       mkdir src
12785 |       touch src/index.ts
12786 |       ```
12787 | 
12788 |       ```powershell Windows
12789 |       # Create a new directory for our project
12790 |       md weather
12791 |       cd weather
12792 | 
12793 |       # Initialize a new npm project
12794 |       npm init -y
12795 | 
12796 |       # Install dependencies
12797 |       npm install @modelcontextprotocol/sdk zod
12798 |       npm install -D @types/node typescript
12799 | 
12800 |       # Create our files
12801 |       md src
12802 |       new-item src\index.ts
12803 |       ```
12804 |     </CodeGroup>
12805 | 
12806 |     Update your package.json to add type: "module" and a build script:
12807 | 
12808 |     ```json package.json
12809 |     {
12810 |       "type": "module",
12811 |       "bin": {
12812 |         "weather": "./build/index.js"
12813 |       },
12814 |       "scripts": {
12815 |         "build": "tsc && chmod 755 build/index.js"
12816 |       },
12817 |       "files": [
12818 |         "build"
12819 |       ],
12820 |     }
12821 |     ```
12822 | 
12823 |     Create a `tsconfig.json` in the root of your project:
12824 | 
12825 |     ```json tsconfig.json
12826 |     {
12827 |       "compilerOptions": {
12828 |         "target": "ES2022",
12829 |         "module": "Node16",
12830 |         "moduleResolution": "Node16",
12831 |         "outDir": "./build",
12832 |         "rootDir": "./src",
12833 |         "strict": true,
12834 |         "esModuleInterop": true,
12835 |         "skipLibCheck": true,
12836 |         "forceConsistentCasingInFileNames": true
12837 |       },
12838 |       "include": ["src/**/*"],
12839 |       "exclude": ["node_modules"]
12840 |     }
12841 |     ```
12842 | 
12843 |     Now let's dive into building your server.
12844 | 
12845 |     ## Building your server
12846 | 
12847 |     ### Importing packages and setting up the instance
12848 | 
12849 |     Add these to the top of your `src/index.ts`:
12850 | 
12851 |     ```typescript
12852 |     import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
12853 |     import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
12854 |     import { z } from "zod";
12855 | 
12856 |     const NWS_API_BASE = "https://api.weather.gov";
12857 |     const USER_AGENT = "weather-app/1.0";
12858 | 
12859 |     // Create server instance
12860 |     const server = new McpServer({
12861 |       name: "weather",
12862 |       version: "1.0.0",
12863 |     });
12864 |     ```
12865 | 
12866 |     ### Helper functions
12867 | 
12868 |     Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
12869 | 
12870 |     ```typescript
12871 |     // Helper function for making NWS API requests
12872 |     async function makeNWSRequest<T>(url: string): Promise<T | null> {
12873 |       const headers = {
12874 |         "User-Agent": USER_AGENT,
12875 |         Accept: "application/geo+json",
12876 |       };
12877 | 
12878 |       try {
12879 |         const response = await fetch(url, { headers });
12880 |         if (!response.ok) {
12881 |           throw new Error(`HTTP error! status: ${response.status}`);
12882 |         }
12883 |         return (await response.json()) as T;
12884 |       } catch (error) {
12885 |         console.error("Error making NWS request:", error);
12886 |         return null;
12887 |       }
12888 |     }
12889 | 
12890 |     interface AlertFeature {
12891 |       properties: {
12892 |         event?: string;
12893 |         areaDesc?: string;
12894 |         severity?: string;
12895 |         status?: string;
12896 |         headline?: string;
12897 |       };
12898 |     }
12899 | 
12900 |     // Format alert data
12901 |     function formatAlert(feature: AlertFeature): string {
12902 |       const props = feature.properties;
12903 |       return [
12904 |         `Event: ${props.event || "Unknown"}`,
12905 |         `Area: ${props.areaDesc || "Unknown"}`,
12906 |         `Severity: ${props.severity || "Unknown"}`,
12907 |         `Status: ${props.status || "Unknown"}`,
12908 |         `Headline: ${props.headline || "No headline"}`,
12909 |         "---",
12910 |       ].join("\n");
12911 |     }
12912 | 
12913 |     interface ForecastPeriod {
12914 |       name?: string;
12915 |       temperature?: number;
12916 |       temperatureUnit?: string;
12917 |       windSpeed?: string;
12918 |       windDirection?: string;
12919 |       shortForecast?: string;
12920 |     }
12921 | 
12922 |     interface AlertsResponse {
12923 |       features: AlertFeature[];
12924 |     }
12925 | 
12926 |     interface PointsResponse {
12927 |       properties: {
12928 |         forecast?: string;
12929 |       };
12930 |     }
12931 | 
12932 |     interface ForecastResponse {
12933 |       properties: {
12934 |         periods: ForecastPeriod[];
12935 |       };
12936 |     }
12937 |     ```
12938 | 
12939 |     ### Implementing tool execution
12940 | 
12941 |     The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
12942 | 
12943 |     ```typescript
12944 |     // Register weather tools
12945 |     server.tool(
12946 |       "get-alerts",
12947 |       "Get weather alerts for a state",
12948 |       {
12949 |         state: z.string().length(2).describe("Two-letter state code (e.g. CA, NY)"),
12950 |       },
12951 |       async ({ state }) => {
12952 |         const stateCode = state.toUpperCase();
12953 |         const alertsUrl = `${NWS_API_BASE}/alerts?area=${stateCode}`;
12954 |         const alertsData = await makeNWSRequest<AlertsResponse>(alertsUrl);
12955 | 
12956 |         if (!alertsData) {
12957 |           return {
12958 |             content: [
12959 |               {
12960 |                 type: "text",
12961 |                 text: "Failed to retrieve alerts data",
12962 |               },
12963 |             ],
12964 |           };
12965 |         }
12966 | 
12967 |         const features = alertsData.features || [];
12968 |         if (features.length === 0) {
12969 |           return {
12970 |             content: [
12971 |               {
12972 |                 type: "text",
12973 |                 text: `No active alerts for ${stateCode}`,
12974 |               },
12975 |             ],
12976 |           };
12977 |         }
12978 | 
12979 |         const formattedAlerts = features.map(formatAlert);
12980 |         const alertsText = `Active alerts for ${stateCode}:\n\n${formattedAlerts.join("\n")}`;
12981 | 
12982 |         return {
12983 |           content: [
12984 |             {
12985 |               type: "text",
12986 |               text: alertsText,
12987 |             },
12988 |           ],
12989 |         };
12990 |       },
12991 |     );
12992 | 
12993 |     server.tool(
12994 |       "get-forecast",
12995 |       "Get weather forecast for a location",
12996 |       {
12997 |         latitude: z.number().min(-90).max(90).describe("Latitude of the location"),
12998 |         longitude: z.number().min(-180).max(180).describe("Longitude of the location"),
12999 |       },
13000 |       async ({ latitude, longitude }) => {
13001 |         // Get grid point data
13002 |         const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(4)},${longitude.toFixed(4)}`;
13003 |         const pointsData = await makeNWSRequest<PointsResponse>(pointsUrl);
13004 | 
13005 |         if (!pointsData) {
13006 |           return {
13007 |             content: [
13008 |               {
13009 |                 type: "text",
13010 |                 text: `Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`,
13011 |               },
13012 |             ],
13013 |           };
13014 |         }
13015 | 
13016 |         const forecastUrl = pointsData.properties?.forecast;
13017 |         if (!forecastUrl) {
13018 |           return {
13019 |             content: [
13020 |               {
13021 |                 type: "text",
13022 |                 text: "Failed to get forecast URL from grid point data",
13023 |               },
13024 |             ],
13025 |           };
13026 |         }
13027 | 
13028 |         // Get forecast data
13029 |         const forecastData = await makeNWSRequest<ForecastResponse>(forecastUrl);
13030 |         if (!forecastData) {
13031 |           return {
13032 |             content: [
13033 |               {
13034 |                 type: "text",
13035 |                 text: "Failed to retrieve forecast data",
13036 |               },
13037 |             ],
13038 |           };
13039 |         }
13040 | 
13041 |         const periods = forecastData.properties?.periods || [];
13042 |         if (periods.length === 0) {
13043 |           return {
13044 |             content: [
13045 |               {
13046 |                 type: "text",
13047 |                 text: "No forecast periods available",
13048 |               },
13049 |             ],
13050 |           };
13051 |         }
13052 | 
13053 |         // Format forecast periods
13054 |         const formattedForecast = periods.map((period: ForecastPeriod) =>
13055 |           [
13056 |             `${period.name || "Unknown"}:`,
13057 |             `Temperature: ${period.temperature || "Unknown"}°${period.temperatureUnit || "F"}`,
13058 |             `Wind: ${period.windSpeed || "Unknown"} ${period.windDirection || ""}`,
13059 |             `${period.shortForecast || "No forecast available"}`,
13060 |             "---",
13061 |           ].join("\n"),
13062 |         );
13063 | 
13064 |         const forecastText = `Forecast for ${latitude}, ${longitude}:\n\n${formattedForecast.join("\n")}`;
13065 | 
13066 |         return {
13067 |           content: [
13068 |             {
13069 |               type: "text",
13070 |               text: forecastText,
13071 |             },
13072 |           ],
13073 |         };
13074 |       },
13075 |     );
13076 |     ```
13077 | 
13078 |     ### Running the server
13079 | 
13080 |     Finally, implement the main function to run the server:
13081 | 
13082 |     ```typescript
13083 |     async function main() {
13084 |       const transport = new StdioServerTransport();
13085 |       await server.connect(transport);
13086 |       console.error("Weather MCP Server running on stdio");
13087 |     }
13088 | 
13089 |     main().catch((error) => {
13090 |       console.error("Fatal error in main():", error);
13091 |       process.exit(1);
13092 |     });
13093 |     ```
13094 | 
13095 |     Make sure to run `npm run build` to build your server! This is a very important step in getting your server to connect.
13096 | 
13097 |     Let's now test your server from an existing MCP host, Claude for Desktop.
13098 | 
13099 |     ## Testing your server with Claude for Desktop
13100 | 
13101 |     <Note>
13102 |       Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/quickstart/client) tutorial to build an MCP client that connects to the server we just built.
13103 |     </Note>
13104 | 
13105 |     First, make sure you have Claude for Desktop installed. [You can install the latest version
13106 |     here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
13107 | 
13108 |     We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
13109 | 
13110 |     For example, if you have [VS Code](https://code.visualstudio.com/) installed:
13111 | 
13112 |     <Tabs>
13113 |       <Tab title="MacOS/Linux">
13114 |         ```bash
13115 |         code ~/Library/Application\ Support/Claude/claude_desktop_config.json
13116 |         ```
13117 |       </Tab>
13118 | 
13119 |       <Tab title="Windows">
13120 |         ```powershell
13121 |         code $env:AppData\Claude\claude_desktop_config.json
13122 |         ```
13123 |       </Tab>
13124 |     </Tabs>
13125 | 
13126 |     You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
13127 | 
13128 |     In this case, we'll add our single weather server like so:
13129 | 
13130 |     <Tabs>
13131 |       <Tab title="MacOS/Linux">
13132 |         <CodeGroup>
13133 |           ```json Node
13134 |           {
13135 |               "mcpServers": {
13136 |                   "weather": {
13137 |                       "command": "node",
13138 |                       "args": [
13139 |                           "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js"
13140 |                       ]
13141 |                   }
13142 |               }
13143 |           }
13144 |           ```
13145 |         </CodeGroup>
13146 |       </Tab>
13147 | 
13148 |       <Tab title="Windows">
13149 |         <CodeGroup>
13150 |           ```json Node
13151 |           {
13152 |               "mcpServers": {
13153 |                   "weather": {
13154 |                       "command": "node",
13155 |                       "args": [
13156 |                           "C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\index.js"
13157 |                       ]
13158 |                   }
13159 |               }
13160 |           }
13161 |           ```
13162 |         </CodeGroup>
13163 |       </Tab>
13164 |     </Tabs>
13165 | 
13166 |     This tells Claude for Desktop:
13167 | 
13168 |     1. There's an MCP server named "weather"
13169 |     2. Launch it by running `node /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js`
13170 | 
13171 |     Save the file, and restart **Claude for Desktop**.
13172 |   </Tab>
13173 | 
13174 |   <Tab title="Java">
13175 |     <Note>
13176 |       This is a quickstart demo based on Spring AI MCP auto-configuration and boot starters.
13177 |       To learn how to create sync and async MCP Servers, manually, consult the [Java SDK Server](/sdk/java/mcp-server) documentation.
13178 |     </Note>
13179 | 
13180 |     Let's get started with building our weather server!
13181 |     [You can find the complete code for what we'll be building here.](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/weather/starter-stdio-server)
13182 | 
13183 |     For more information, see the [MCP Server Boot Starter](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html) reference documentation.
13184 |     For manual MCP Server implementation, refer to the [MCP Server Java SDK documentation](/sdk/java/mcp-server).
13185 | 
13186 |     ### System requirements
13187 | 
13188 |     * Java 17 or higher installed.
13189 |     * [Spring Boot 3.3.x](https://docs.spring.io/spring-boot/installing.html) or higher
13190 | 
13191 |     ### Set up your environment
13192 | 
13193 |     Use the [Spring Initizer](https://start.spring.io/) to bootstrat the project.
13194 | 
13195 |     You will need to add the following dependencies:
13196 | 
13197 |     <Tabs>
13198 |       <Tab title="Maven">
13199 |         ```xml
13200 |         <dependencies>
13201 |               <dependency>
13202 |                   <groupId>org.springframework.ai</groupId>
13203 |                   <artifactId>spring-ai-mcp-server-spring-boot-starter</artifactId>
13204 |               </dependency>
13205 | 
13206 |               <dependency>
13207 |                   <groupId>org.springframework</groupId>
13208 |                   <artifactId>spring-web</artifactId>
13209 |               </dependency>
13210 |         </dependencies>
13211 |         ```
13212 |       </Tab>
13213 | 
13214 |       <Tab title="Gradle">
13215 |         ```groovy
13216 |         dependencies {
13217 |           implementation platform("org.springframework.ai:spring-ai-mcp-server-spring-boot-starter")
13218 |           implementation platform("org.springframework:spring-web")   
13219 |         }
13220 |         ```
13221 |       </Tab>
13222 |     </Tabs>
13223 | 
13224 |     Then configure your application by setting the applicaiton properties:
13225 | 
13226 |     <CodeGroup>
13227 |       ```bash application.properties
13228 |       spring.main.bannerMode=off
13229 |       logging.pattern.console=
13230 |       ```
13231 | 
13232 |       ```yaml application.yml
13233 |       logging:
13234 |         pattern:
13235 |           console:
13236 |       spring:
13237 |         main:
13238 |           banner-mode: off
13239 |       ```
13240 |     </CodeGroup>
13241 | 
13242 |     The [Server Configuration Properties](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html#_configuration_properties) documents all available properties.
13243 | 
13244 |     Now let's dive into building your server.
13245 | 
13246 |     ## Building your server
13247 | 
13248 |     ### Weather Service
13249 | 
13250 |     Let's implement a [WeatheService.java](https://github.com/spring-projects/spring-ai-examples/blob/main/model-context-protocol/weather/starter-stdio-server/src/main/java/org/springframework/ai/mcp/sample/server/WeatherService.java) that uses a REST client to query the data from the National Weather Service API:
13251 | 
13252 |     ```java
13253 |     @Service
13254 |     public class WeatherService {
13255 | 
13256 |     	private final RestClient restClient;
13257 | 
13258 |     	public WeatherService() {
13259 |     		this.restClient = RestClient.builder()
13260 |     			.baseUrl("https://api.weather.gov")
13261 |     			.defaultHeader("Accept", "application/geo+json")
13262 |     			.defaultHeader("User-Agent", "WeatherApiClient/1.0 ([email protected])")
13263 |     			.build();
13264 |     	}
13265 | 
13266 |       @Tool(description = "Get weather forecast for a specific latitude/longitude")
13267 |       public String getWeatherForecastByLocation(
13268 |           double latitude,   // Latitude coordinate
13269 |           double longitude   // Longitude coordinate
13270 |       ) {
13271 |           // Returns detailed forecast including:
13272 |           // - Temperature and unit
13273 |           // - Wind speed and direction
13274 |           // - Detailed forecast description
13275 |       }
13276 |     	
13277 |       @Tool(description = "Get weather alerts for a US state")
13278 |       public String getAlerts(
13279 |           @ToolParam(description = "Two-letter US state code (e.g. CA, NY") String state)
13280 |       ) {
13281 |           // Returns active alerts including:
13282 |           // - Event type
13283 |           // - Affected area
13284 |           // - Severity
13285 |           // - Description
13286 |           // - Safety instructions
13287 |       }
13288 | 
13289 |       // ......
13290 |     }
13291 |     ```
13292 | 
13293 |     The `@Service` annotation with auto-register the service in your applicaiton context.
13294 |     The Spring AI `@Tool` annotation, making it easy to create and maintain MCP tools.
13295 | 
13296 |     The auto-configuration will automatically register these tools with the MCP server.
13297 | 
13298 |     ### Create your Boot Applicaiton
13299 | 
13300 |     ```java
13301 |     @SpringBootApplication
13302 |     public class McpServerApplication {
13303 | 
13304 |     	public static void main(String[] args) {
13305 |     		SpringApplication.run(McpServerApplication.class, args);
13306 |     	}
13307 | 
13308 |     	@Bean
13309 |     	public ToolCallbackProvider weatherTools(WeatherService weatherService) {
13310 |     		return  MethodToolCallbackProvider.builder().toolObjects(weatherService).build();
13311 |     	}
13312 |     }
13313 |     ```
13314 | 
13315 |     Uses the the `MethodToolCallbackProvider` utils to convert the `@Tools` into actionalble callbackes used by the MCP server.
13316 | 
13317 |     ### Running the server
13318 | 
13319 |     Finally, let's build the server:
13320 | 
13321 |     ```bash
13322 |     ./mvnw clean install
13323 |     ```
13324 | 
13325 |     This will generate a `mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar` file within the `target` folder.
13326 | 
13327 |     Let's now test your server from an existing MCP host, Claude for Desktop.
13328 | 
13329 |     ## Testing your server with Claude for Desktop
13330 | 
13331 |     <Note>
13332 |       Claude for Desktop is not yet available on Linux.
13333 |     </Note>
13334 | 
13335 |     First, make sure you have Claude for Desktop installed.
13336 |     [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
13337 | 
13338 |     We'll need to configure Claude for Desktop for whichever MCP servers you want to use.
13339 |     To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor.
13340 |     Make sure to create the file if it doesn't exist.
13341 | 
13342 |     For example, if you have [VS Code](https://code.visualstudio.com/) installed:
13343 | 
13344 |     <Tabs>
13345 |       <Tab title="MacOS/Linux">
13346 |         ```bash
13347 |         code ~/Library/Application\ Support/Claude/claude_desktop_config.json
13348 |         ```
13349 |       </Tab>
13350 | 
13351 |       <Tab title="Windows">
13352 |         ```powershell
13353 |         code $env:AppData\Claude\claude_desktop_config.json
13354 |         ```
13355 |       </Tab>
13356 |     </Tabs>
13357 | 
13358 |     You'll then add your servers in the `mcpServers` key.
13359 |     The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
13360 | 
13361 |     In this case, we'll add our single weather server like so:
13362 | 
13363 |     <Tabs>
13364 |       <Tab title="MacOS/Linux">
13365 |         ```json java
13366 |         {
13367 |           "mcpServers": {
13368 |             "spring-ai-mcp-weather": {
13369 |               "command": "java",
13370 |               "args": [
13371 |                 "-Dspring.ai.mcp.server.stdio=true",
13372 |                 "-jar",
13373 |                 "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar"
13374 |               ]
13375 |             }
13376 |           }
13377 |         }
13378 |         ```
13379 |       </Tab>
13380 | 
13381 |       <Tab title="Windows">
13382 |         ```json java
13383 |         {
13384 |           "mcpServers": {
13385 |             "spring-ai-mcp-weather": {
13386 |               "command": "java",
13387 |               "args": [
13388 |                 "-Dspring.ai.mcp.server.transport=STDIO",
13389 |                 "-jar",
13390 |                 "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar"
13391 |               ]
13392 |             }
13393 |           }
13394 |         }
13395 |         ```
13396 |       </Tab>
13397 |     </Tabs>
13398 | 
13399 |     <Note>
13400 |       Make sure you pass in the absolute path to your server.
13401 |     </Note>
13402 | 
13403 |     This tells Claude for Desktop:
13404 | 
13405 |     1. There's an MCP server named "my-weather-server"
13406 |     2. To launch it by running `java -jar /ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar`
13407 | 
13408 |     Save the file, and restart **Claude for Desktop**.
13409 | 
13410 |     ## Testing your server with Java client
13411 | 
13412 |     ### Create a MCP Client manually
13413 | 
13414 |     Use the `McpClient` to connect to the server:
13415 | 
13416 |     ```java
13417 |     var stdioParams = ServerParameters.builder("java")
13418 |       .args("-jar", "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar")
13419 |       .build();
13420 | 
13421 |     var stdioTransport = new StdioClientTransport(stdioParams);
13422 | 
13423 |     var mcpClient = McpClient.sync(stdioTransport).build();
13424 | 
13425 |     mcpClient.initialize();
13426 | 
13427 |     ListToolsResult toolsList = mcpClient.listTools();
13428 | 
13429 |     CallToolResult weather = mcpClient.callTool(
13430 |       new CallToolRequest("getWeatherForecastByLocation",
13431 |           Map.of("latitude", "47.6062", "longitude", "-122.3321")));
13432 | 
13433 |     CallToolResult alert = mcpClient.callTool(
13434 |       new CallToolRequest("getAlerts", Map.of("state", "NY")));
13435 | 
13436 |     mcpClient.closeGracefully();
13437 |     ```
13438 | 
13439 |     ### Use MCP Client Boot Starter
13440 | 
13441 |     Create a new boot starter applicaiton using the `spring-ai-mcp-client-spring-boot-starter` dependency:
13442 | 
13443 |     ```xml
13444 |     <dependency>
13445 |         <groupId>org.springframework.ai</groupId>
13446 |         <artifactId>spring-ai-mcp-client-spring-boot-starter</artifactId>
13447 |     </dependency>
13448 |     ```
13449 | 
13450 |     and set the `spring.ai.mcp.client.stdio.servers-configuration` property to point to your `claude_desktop_config.json`.
13451 |     You can re-use the existing Anthropic Destop configuration:
13452 | 
13453 |     ```properties
13454 |     spring.ai.mcp.client.stdio.servers-configuration=file:PATH/TO/claude_desktop_config.json
13455 |     ```
13456 | 
13457 |     When you stasrt your client applicaiton, the auto-configuration will create, automatically MCP clients from the claude\_desktop\_config.json.
13458 | 
13459 |     For more information, see the [MCP Client Boot Starters](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-client-docs.html) reference documentation.
13460 | 
13461 |     ## More Java MCP Server examples
13462 | 
13463 |     The [starter-webflux-server](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/weather/starter-webflux-server) demonstrates how to create a MCP server using SSE transport.
13464 |     It showcases how to define and register MCP Tools, Resources, and Prompts, using the Spring Boot's auto-configuration capabilities.
13465 |   </Tab>
13466 | </Tabs>
13467 | 
13468 | ### Test with commands
13469 | 
13470 | Let's make sure Claude for Desktop is picking up the two tools we've exposed in our `weather` server. You can do this by looking for the hammer <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/claude-desktop-mcp-hammer-icon.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon:
13471 | 
13472 | <Frame>
13473 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/visual-indicator-mcp-tools.png" />
13474 | </Frame>
13475 | 
13476 | After clicking on the hammer icon, you should see two tools listed:
13477 | 
13478 | <Frame>
13479 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/available-mcp-tools.png" />
13480 | </Frame>
13481 | 
13482 | If your server isn't being picked up by Claude for Desktop, proceed to the [Troubleshooting](#troubleshooting) section for debugging tips.
13483 | 
13484 | If the hammer icon has shown up, you can now test your server by running the following commands in Claude for Desktop:
13485 | 
13486 | * What's the weather in Sacramento?
13487 | * What are the active weather alerts in Texas?
13488 | 
13489 | <Frame>
13490 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/current-weather.png" />
13491 | </Frame>
13492 | 
13493 | <Frame>
13494 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/weather-alerts.png" />
13495 | </Frame>
13496 | 
13497 | <Note>
13498 |   Since this is the US National Weather service, the queries will only work for US locations.
13499 | </Note>
13500 | 
13501 | ## What's happening under the hood
13502 | 
13503 | When you ask a question:
13504 | 
13505 | 1. The client sends your question to Claude
13506 | 2. Claude analyzes the available tools and decides which one(s) to use
13507 | 3. The client executes the chosen tool(s) through the MCP server
13508 | 4. The results are sent back to Claude
13509 | 5. Claude formulates a natural language response
13510 | 6. The response is displayed to you!
13511 | 
13512 | ## Troubleshooting
13513 | 
13514 | <AccordionGroup>
13515 |   <Accordion title="Claude for Desktop Integration Issues">
13516 |     **Getting logs from Claude for Desktop**
13517 | 
13518 |     Claude.app logging related to MCP is written to log files in `~/Library/Logs/Claude`:
13519 | 
13520 |     * `mcp.log` will contain general logging about MCP connections and connection failures.
13521 |     * Files named `mcp-server-SERVERNAME.log` will contain error (stderr) logging from the named server.
13522 | 
13523 |     You can run the following command to list recent logs and follow along with any new ones:
13524 | 
13525 |     ```bash
13526 |     # Check Claude's logs for errors
13527 |     tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
13528 |     ```
13529 | 
13530 |     **Server not showing up in Claude**
13531 | 
13532 |     1. Check your `claude_desktop_config.json` file syntax
13533 |     2. Make sure the path to your project is absolute and not relative
13534 |     3. Restart Claude for Desktop completely
13535 | 
13536 |     **Tool calls failing silently**
13537 | 
13538 |     If Claude attempts to use the tools but they fail:
13539 | 
13540 |     1. Check Claude's logs for errors
13541 |     2. Verify your server builds and runs without errors
13542 |     3. Try restarting Claude for Desktop
13543 | 
13544 |     **None of this is working. What do I do?**
13545 | 
13546 |     Please refer to our [debugging guide](/docs/tools/debugging) for better debugging tools and more detailed guidance.
13547 |   </Accordion>
13548 | 
13549 |   <Accordion title="Weather API Issues">
13550 |     **Error: Failed to retrieve grid point data**
13551 | 
13552 |     This usually means either:
13553 | 
13554 |     1. The coordinates are outside the US
13555 |     2. The NWS API is having issues
13556 |     3. You're being rate limited
13557 | 
13558 |     Fix:
13559 | 
13560 |     * Verify you're using US coordinates
13561 |     * Add a small delay between requests
13562 |     * Check the NWS API status page
13563 | 
13564 |     **Error: No active alerts for \[STATE]**
13565 | 
13566 |     This isn't an error - it just means there are no current weather alerts for that state. Try a different state or check during severe weather.
13567 |   </Accordion>
13568 | </AccordionGroup>
13569 | 
13570 | <Note>
13571 |   For more advanced troubleshooting, check out our guide on [Debugging MCP](/docs/tools/debugging)
13572 | </Note>
13573 | 
13574 | ## Next steps
13575 | 
13576 | <CardGroup cols={2}>
13577 |   <Card title="Building a client" icon="outlet" href="/quickstart/client">
13578 |     Learn how to build your own MCP client that can connect to your server
13579 |   </Card>
13580 | 
13581 |   <Card title="Example servers" icon="grid" href="/examples">
13582 |     Check out our gallery of official MCP servers and implementations
13583 |   </Card>
13584 | 
13585 |   <Card title="Debugging Guide" icon="bug" href="/docs/tools/debugging">
13586 |     Learn how to effectively debug MCP servers and integrations
13587 |   </Card>
13588 | 
13589 |   <Card title="Building MCP with LLMs" icon="comments" href="/tutorials/building-mcp-with-llms">
13590 |     Learn how to use LLMs like Claude to speed up your MCP development
13591 |   </Card>
13592 | </CardGroup>
13593 | 
13594 | 
13595 | # For Claude Desktop Users
13596 | Source: https://modelcontextprotocol.io/quickstart/user
13597 | 
13598 | Get started using pre-built servers in Claude for Desktop.
13599 | 
13600 | In this tutorial, you will extend [Claude for Desktop](https://claude.ai/download) so that it can read from your computer's file system, write new files, move files, and even search files.
13601 | 
13602 | <Frame>
13603 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-filesystem.png" />
13604 | </Frame>
13605 | 
13606 | Don't worry — it will ask you for your permission before executing these actions!
13607 | 
13608 | ## 1. Download Claude for Desktop
13609 | 
13610 | Start by downloading [Claude for Desktop](https://claude.ai/download), choosing either macOS or Windows. (Linux is not yet supported for Claude for Desktop.)
13611 | 
13612 | Follow the installation instructions.
13613 | 
13614 | If you already have Claude for Desktop, make sure it's on the latest version by clicking on the Claude menu on your computer and selecting "Check for Updates..."
13615 | 
13616 | <Accordion title="Why Claude for Desktop and not Claude.ai?">
13617 |   Because servers are locally run, MCP currently only supports desktop hosts. Remote hosts are in active development.
13618 | </Accordion>
13619 | 
13620 | ## 2. Add the Filesystem MCP Server
13621 | 
13622 | To add this filesystem functionality, we will be installing a pre-built [Filesystem MCP Server](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem) to Claude for Desktop. This is one of dozens of [servers](https://github.com/modelcontextprotocol/servers/tree/main) created by Anthropic and the community.
13623 | 
13624 | Get started by opening up the Claude menu on your computer and select "Settings..." Please note that these are not the Claude Account Settings found in the app window itself.
13625 | 
13626 | This is what it should look like on a Mac:
13627 | 
13628 | <Frame style={{ textAlign: 'center' }}>
13629 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-menu.png" width="400" />
13630 | </Frame>
13631 | 
13632 | Click on "Developer" in the lefthand bar of the Settings pane, and then click on "Edit Config":
13633 | 
13634 | <Frame>
13635 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-developer.png" />
13636 | </Frame>
13637 | 
13638 | This will create a configuration file at:
13639 | 
13640 | * macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
13641 | * Windows: `%APPDATA%\Claude\claude_desktop_config.json`
13642 | 
13643 | if you don't already have one, and will display the file in your file system.
13644 | 
13645 | Open up the configuration file in any text editor. Replace the file contents with this:
13646 | 
13647 | <Tabs>
13648 |   <Tab title="MacOS/Linux">
13649 |     ```json
13650 |     {
13651 |       "mcpServers": {
13652 |         "filesystem": {
13653 |           "command": "npx",
13654 |           "args": [
13655 |             "-y",
13656 |             "@modelcontextprotocol/server-filesystem",
13657 |             "/Users/username/Desktop",
13658 |             "/Users/username/Downloads"
13659 |           ]
13660 |         }
13661 |       }
13662 |     }
13663 |     ```
13664 |   </Tab>
13665 | 
13666 |   <Tab title="Windows">
13667 |     ```json
13668 |     {
13669 |       "mcpServers": {
13670 |         "filesystem": {
13671 |           "command": "npx",
13672 |           "args": [
13673 |             "-y",
13674 |             "@modelcontextprotocol/server-filesystem",
13675 |             "C:\\Users\\username\\Desktop",
13676 |             "C:\\Users\\username\\Downloads"
13677 |           ]
13678 |         }
13679 |       }
13680 |     }
13681 |     ```
13682 |   </Tab>
13683 | </Tabs>
13684 | 
13685 | Make sure to replace `username` with your computer's username. The paths should point to valid directories that you want Claude to be able to access and modify. It's set up to work for Desktop and Downloads, but you can add more paths as well.
13686 | 
13687 | You will also need [Node.js](https://nodejs.org) on your computer for this to run properly. To verify you have Node installed, open the command line on your computer.
13688 | 
13689 | * On macOS, open the Terminal from your Applications folder
13690 | * On Windows, press Windows + R, type "cmd", and press Enter
13691 | 
13692 | Once in the command line, verify you have Node installed by entering in the following command:
13693 | 
13694 | ```bash
13695 | node --version
13696 | ```
13697 | 
13698 | If you get an error saying "command not found" or "node is not recognized", download Node from [nodejs.org](https://nodejs.org/).
13699 | 
13700 | <Tip>
13701 |   **How does the configuration file work?**
13702 | 
13703 |   This configuration file tells Claude for Desktop which MCP servers to start up every time you start the application. In this case, we have added one server called "filesystem" that will use the Node `npx` command to install and run `@modelcontextprotocol/server-filesystem`. This server, described [here](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem), will let you access your file system in Claude for Desktop.
13704 | </Tip>
13705 | 
13706 | <Warning>
13707 |   **Command Privileges**
13708 | 
13709 |   Claude for Desktop will run the commands in the configuration file with the permissions of your user account, and access to your local files. Only add commands if you understand and trust the source.
13710 | </Warning>
13711 | 
13712 | ## 3. Restart Claude
13713 | 
13714 | After updating your configuration file, you need to restart Claude for Desktop.
13715 | 
13716 | Upon restarting, you should see a hammer <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/claude-desktop-mcp-hammer-icon.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon in the bottom right corner of the input box:
13717 | 
13718 | <Frame>
13719 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-hammer.png" />
13720 | </Frame>
13721 | 
13722 | After clicking on the hammer icon, you should see the tools that come with the Filesystem MCP Server:
13723 | 
13724 | <Frame style={{ textAlign: 'center' }}>
13725 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-tools.png" width="400" />
13726 | </Frame>
13727 | 
13728 | If your server isn't being picked up by Claude for Desktop, proceed to the [Troubleshooting](#troubleshooting) section for debugging tips.
13729 | 
13730 | ## 4. Try it out!
13731 | 
13732 | You can now talk to Claude and ask it about your filesystem. It should know when to call the relevant tools.
13733 | 
13734 | Things you might try asking Claude:
13735 | 
13736 | * Can you write a poem and save it to my desktop?
13737 | * What are some work-related files in my downloads folder?
13738 | * Can you take all the images on my desktop and move them to a new folder called "Images"?
13739 | 
13740 | As needed, Claude will call the relevant tools and seek your approval before taking an action:
13741 | 
13742 | <Frame style={{ textAlign: 'center' }}>
13743 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-approve.png" width="500" />
13744 | </Frame>
13745 | 
13746 | ## Troubleshooting
13747 | 
13748 | <AccordionGroup>
13749 |   <Accordion title="Server not showing up in Claude / hammer icon missing">
13750 |     1. Restart Claude for Desktop completely
13751 |     2. Check your `claude_desktop_config.json` file syntax
13752 |     3. Make sure the file paths included in `claude_desktop_config.json` are valid and that they are absolute and not relative
13753 |     4. Look at [logs](#getting-logs-from-claude-for-desktop) to see why the server is not connecting
13754 |     5. In your command line, try manually running the server (replacing `username` as you did in `claude_desktop_config.json`) to see if you get any errors:
13755 | 
13756 |     <Tabs>
13757 |       <Tab title="MacOS/Linux">
13758 |         ```bash
13759 |         npx -y @modelcontextprotocol/server-filesystem /Users/username/Desktop /Users/username/Downloads
13760 |         ```
13761 |       </Tab>
13762 | 
13763 |       <Tab title="Windows">
13764 |         ```bash
13765 |         npx -y @modelcontextprotocol/server-filesystem C:\Users\username\Desktop C:\Users\username\Downloads
13766 |         ```
13767 |       </Tab>
13768 |     </Tabs>
13769 |   </Accordion>
13770 | 
13771 |   <Accordion title="Getting logs from Claude for Desktop">
13772 |     Claude.app logging related to MCP is written to log files in:
13773 | 
13774 |     * macOS: `~/Library/Logs/Claude`
13775 | 
13776 |     * Windows: `%APPDATA%\Claude\logs`
13777 | 
13778 |     * `mcp.log` will contain general logging about MCP connections and connection failures.
13779 | 
13780 |     * Files named `mcp-server-SERVERNAME.log` will contain error (stderr) logging from the named server.
13781 | 
13782 |     You can run the following command to list recent logs and follow along with any new ones (on Windows, it will only show recent logs):
13783 | 
13784 |     <Tabs>
13785 |       <Tab title="MacOS/Linux">
13786 |         ```bash
13787 |         # Check Claude's logs for errors
13788 |         tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
13789 |         ```
13790 |       </Tab>
13791 | 
13792 |       <Tab title="Windows">
13793 |         ```bash
13794 |         type "%APPDATA%\Claude\logs\mcp*.log"
13795 |         ```
13796 |       </Tab>
13797 |     </Tabs>
13798 |   </Accordion>
13799 | 
13800 |   <Accordion title="Tool calls failing silently">
13801 |     If Claude attempts to use the tools but they fail:
13802 | 
13803 |     1. Check Claude's logs for errors
13804 |     2. Verify your server builds and runs without errors
13805 |     3. Try restarting Claude for Desktop
13806 |   </Accordion>
13807 | 
13808 |   <Accordion title="None of this is working. What do I do?">
13809 |     Please refer to our [debugging guide](/docs/tools/debugging) for better debugging tools and more detailed guidance.
13810 |   </Accordion>
13811 | 
13812 |   <Accordion title="ENOENT error and `${APPDATA}` in paths on Windows">
13813 |     If your configured server fails to load, and you see within its logs an error referring to `${APPDATA}` within a path, you may need to add the expanded value of `%APPDATA%` to your `env` key in `claude_desktop_config.json`:
13814 | 
13815 |     ```json
13816 |     {
13817 |       "brave-search": {
13818 |         "command": "npx",
13819 |         "args": ["-y", "@modelcontextprotocol/server-brave-search"],
13820 |         "env": {
13821 |           "APPDATA": "C:\\Users\\user\\AppData\\Roaming\\",
13822 |           "BRAVE_API_KEY": "..."
13823 |         }
13824 |       }
13825 |     }
13826 |     ```
13827 | 
13828 |     With this change in place, launch Claude Desktop once again.
13829 | 
13830 |     <Warning>
13831 |       **NPM should be installed globally**
13832 | 
13833 |       The `npx` command may continue to fail if you have not installed NPM globally. If NPM is already installed globally, you will find `%APPDATA%\npm` exists on your system. If not, you can install NPM globally by running the following command:
13834 | 
13835 |       ```bash
13836 |       npm install -g npm
13837 |       ```
13838 |     </Warning>
13839 |   </Accordion>
13840 | </AccordionGroup>
13841 | 
13842 | ## Next steps
13843 | 
13844 | <CardGroup cols={2}>
13845 |   <Card title="Explore other servers" icon="grid" href="/examples">
13846 |     Check out our gallery of official MCP servers and implementations
13847 |   </Card>
13848 | 
13849 |   <Card title="Build your own server" icon="code" href="/quickstart/server">
13850 |     Now build your own custom server to use in Claude for Desktop and other clients
13851 |   </Card>
13852 | </CardGroup>
13853 | 
13854 | 
13855 | # MCP Client
13856 | Source: https://modelcontextprotocol.io/sdk/java/mcp-client
13857 | 
13858 | Learn how to use the Model Context Protocol (MCP) client to interact with MCP servers
13859 | 
13860 | # Model Context Protocol Client
13861 | 
13862 | The MCP Client is a key component in the Model Context Protocol (MCP) architecture, responsible for establishing and managing connections with MCP servers. It implements the client-side of the protocol, handling:
13863 | 
13864 | * Protocol version negotiation to ensure compatibility with servers
13865 | * Capability negotiation to determine available features
13866 | * Message transport and JSON-RPC communication
13867 | * Tool discovery and execution
13868 | * Resource access and management
13869 | * Prompt system interactions
13870 | * Optional features like roots management and sampling support
13871 | 
13872 | The client provides both synchronous and asynchronous APIs for flexibility in different application contexts.
13873 | 
13874 | <Tabs>
13875 |   <Tab title="Sync API">
13876 |     ```java
13877 |     // Create a sync client with custom configuration
13878 |     McpSyncClient client = McpClient.sync(transport)
13879 |         .requestTimeout(Duration.ofSeconds(10))
13880 |         .capabilities(ClientCapabilities.builder()
13881 |             .roots(true)      // Enable roots capability
13882 |             .sampling()       // Enable sampling capability
13883 |             .build())
13884 |         .sampling(request -> new CreateMessageResult(response))
13885 |         .build();
13886 | 
13887 |     // Initialize connection
13888 |     client.initialize();
13889 | 
13890 |     // List available tools
13891 |     ListToolsResult tools = client.listTools();
13892 | 
13893 |     // Call a tool
13894 |     CallToolResult result = client.callTool(
13895 |         new CallToolRequest("calculator", 
13896 |             Map.of("operation", "add", "a", 2, "b", 3))
13897 |     );
13898 | 
13899 |     // List and read resources
13900 |     ListResourcesResult resources = client.listResources();
13901 |     ReadResourceResult resource = client.readResource(
13902 |         new ReadResourceRequest("resource://uri")
13903 |     );
13904 | 
13905 |     // List and use prompts
13906 |     ListPromptsResult prompts = client.listPrompts();
13907 |     GetPromptResult prompt = client.getPrompt(
13908 |         new GetPromptRequest("greeting", Map.of("name", "Spring"))
13909 |     );
13910 | 
13911 |     // Add/remove roots
13912 |     client.addRoot(new Root("file:///path", "description"));
13913 |     client.removeRoot("file:///path");
13914 | 
13915 |     // Close client
13916 |     client.closeGracefully();
13917 |     ```
13918 |   </Tab>
13919 | 
13920 |   <Tab title="Async API">
13921 |     ```java
13922 |     // Create an async client with custom configuration
13923 |     McpAsyncClient client = McpClient.async(transport)
13924 |         .requestTimeout(Duration.ofSeconds(10))
13925 |         .capabilities(ClientCapabilities.builder()
13926 |             .roots(true)      // Enable roots capability
13927 |             .sampling()       // Enable sampling capability
13928 |             .build())
13929 |         .sampling(request -> Mono.just(new CreateMessageResult(response)))
13930 |         .toolsChangeConsumer(tools -> Mono.fromRunnable(() -> {
13931 |             logger.info("Tools updated: {}", tools);
13932 |         }))
13933 |         .resourcesChangeConsumer(resources -> Mono.fromRunnable(() -> {
13934 |             logger.info("Resources updated: {}", resources);
13935 |         }))
13936 |         .promptsChangeConsumer(prompts -> Mono.fromRunnable(() -> {
13937 |             logger.info("Prompts updated: {}", prompts);
13938 |         }))
13939 |         .build();
13940 | 
13941 |     // Initialize connection and use features
13942 |     client.initialize()
13943 |         .flatMap(initResult -> client.listTools())
13944 |         .flatMap(tools -> {
13945 |             return client.callTool(new CallToolRequest(
13946 |                 "calculator", 
13947 |                 Map.of("operation", "add", "a", 2, "b", 3)
13948 |             ));
13949 |         })
13950 |         .flatMap(result -> {
13951 |             return client.listResources()
13952 |                 .flatMap(resources -> 
13953 |                     client.readResource(new ReadResourceRequest("resource://uri"))
13954 |                 );
13955 |         })
13956 |         .flatMap(resource -> {
13957 |             return client.listPrompts()
13958 |                 .flatMap(prompts ->
13959 |                     client.getPrompt(new GetPromptRequest(
13960 |                         "greeting", 
13961 |                         Map.of("name", "Spring")
13962 |                     ))
13963 |                 );
13964 |         })
13965 |         .flatMap(prompt -> {
13966 |             return client.addRoot(new Root("file:///path", "description"))
13967 |                 .then(client.removeRoot("file:///path"));            
13968 |         })
13969 |         .doFinally(signalType -> {
13970 |             client.closeGracefully().subscribe();
13971 |         })
13972 |         .subscribe();
13973 |     ```
13974 |   </Tab>
13975 | </Tabs>
13976 | 
13977 | ## Client Transport
13978 | 
13979 | The transport layer handles the communication between MCP clients and servers, providing different implementations for various use cases. The client transport manages message serialization, connection establishment, and protocol-specific communication patterns.
13980 | 
13981 | <Tabs>
13982 |   <Tab title="STDIO">
13983 |     Creates transport for in-process based communication
13984 | 
13985 |     ```java
13986 |     ServerParameters params = ServerParameters.builder("npx")
13987 |         .args("-y", "@modelcontextprotocol/server-everything", "dir")
13988 |         .build();
13989 |     McpTransport transport = new StdioClientTransport(params);
13990 |     ```
13991 |   </Tab>
13992 | 
13993 |   <Tab title="SSE (HttpClient)">
13994 |     Creates a framework agnostic (pure Java API) SSE client transport. Included in the core mcp module.
13995 | 
13996 |     ```java
13997 |     McpTransport transport = new HttpClientSseClientTransport("http://your-mcp-server");
13998 |     ```
13999 |   </Tab>
14000 | 
14001 |   <Tab title="SSE (WebFlux)">
14002 |     Creates WebFlux-based SSE client transport. Requires the mcp-webflux-sse-transport dependency.
14003 | 
14004 |     ```java
14005 |     WebClient.Builder webClientBuilder = WebClient.builder()
14006 |         .baseUrl("http://your-mcp-server");
14007 |     McpTransport transport = new WebFluxSseClientTransport(webClientBuilder);
14008 |     ```
14009 |   </Tab>
14010 | </Tabs>
14011 | 
14012 | ## Client Capabilities
14013 | 
14014 | The client can be configured with various capabilities:
14015 | 
14016 | ```java
14017 | var capabilities = ClientCapabilities.builder()
14018 |     .roots(true)      // Enable filesystem roots support with list changes notifications
14019 |     .sampling()       // Enable LLM sampling support
14020 |     .build();
14021 | ```
14022 | 
14023 | ### Roots Support
14024 | 
14025 | Roots define the boundaries of where servers can operate within the filesystem:
14026 | 
14027 | ```java
14028 | // Add a root dynamically
14029 | client.addRoot(new Root("file:///path", "description"));
14030 | 
14031 | // Remove a root
14032 | client.removeRoot("file:///path");
14033 | 
14034 | // Notify server of roots changes
14035 | client.rootsListChangedNotification();
14036 | ```
14037 | 
14038 | The roots capability allows servers to:
14039 | 
14040 | * Request the list of accessible filesystem roots
14041 | * Receive notifications when the roots list changes
14042 | * Understand which directories and files they have access to
14043 | 
14044 | ### Sampling Support
14045 | 
14046 | Sampling enables servers to request LLM interactions ("completions" or "generations") through the client:
14047 | 
14048 | ```java
14049 | // Configure sampling handler
14050 | Function<CreateMessageRequest, CreateMessageResult> samplingHandler = request -> {
14051 |     // Sampling implementation that interfaces with LLM
14052 |     return new CreateMessageResult(response);
14053 | };
14054 | 
14055 | // Create client with sampling support
14056 | var client = McpClient.sync(transport)
14057 |     .capabilities(ClientCapabilities.builder()
14058 |         .sampling()
14059 |         .build())
14060 |     .sampling(samplingHandler)
14061 |     .build();
14062 | ```
14063 | 
14064 | This capability allows:
14065 | 
14066 | * Servers to leverage AI capabilities without requiring API keys
14067 | * Clients to maintain control over model access and permissions
14068 | * Support for both text and image-based interactions
14069 | * Optional inclusion of MCP server context in prompts
14070 | 
14071 | ## Using MCP Clients
14072 | 
14073 | ### Tool Execution
14074 | 
14075 | Tools are server-side functions that clients can discover and execute. The MCP client provides methods to list available tools and execute them with specific parameters. Each tool has a unique name and accepts a map of parameters.
14076 | 
14077 | <Tabs>
14078 |   <Tab title="Sync API">
14079 |     ```java
14080 |     // List available tools and their names
14081 |     var tools = client.listTools();
14082 |     tools.forEach(tool -> System.out.println(tool.getName()));
14083 | 
14084 |     // Execute a tool with parameters
14085 |     var result = client.callTool("calculator", Map.of(
14086 |         "operation", "add",
14087 |         "a", 1,
14088 |         "b", 2
14089 |     ));
14090 |     ```
14091 |   </Tab>
14092 | 
14093 |   <Tab title="Async API">
14094 |     ```java
14095 |     // List available tools asynchronously
14096 |     client.listTools()
14097 |         .doOnNext(tools -> tools.forEach(tool -> 
14098 |             System.out.println(tool.getName())))
14099 |         .subscribe();
14100 | 
14101 |     // Execute a tool asynchronously
14102 |     client.callTool("calculator", Map.of(
14103 |             "operation", "add",
14104 |             "a", 1,
14105 |             "b", 2
14106 |         ))
14107 |         .subscribe();
14108 |     ```
14109 |   </Tab>
14110 | </Tabs>
14111 | 
14112 | ### Resource Access
14113 | 
14114 | Resources represent server-side data sources that clients can access using URI templates. The MCP client provides methods to discover available resources and retrieve their contents through a standardized interface.
14115 | 
14116 | <Tabs>
14117 |   <Tab title="Sync API">
14118 |     ```java
14119 |     // List available resources and their names
14120 |     var resources = client.listResources();
14121 |     resources.forEach(resource -> System.out.println(resource.getName()));
14122 | 
14123 |     // Retrieve resource content using a URI template
14124 |     var content = client.getResource("file", Map.of(
14125 |         "path", "/path/to/file.txt"
14126 |     ));
14127 |     ```
14128 |   </Tab>
14129 | 
14130 |   <Tab title="Async API">
14131 |     ```java
14132 |     // List available resources asynchronously
14133 |     client.listResources()
14134 |         .doOnNext(resources -> resources.forEach(resource -> 
14135 |             System.out.println(resource.getName())))
14136 |         .subscribe();
14137 | 
14138 |     // Retrieve resource content asynchronously
14139 |     client.getResource("file", Map.of(
14140 |             "path", "/path/to/file.txt"
14141 |         ))
14142 |         .subscribe();
14143 |     ```
14144 |   </Tab>
14145 | </Tabs>
14146 | 
14147 | ### Prompt System
14148 | 
14149 | The prompt system enables interaction with server-side prompt templates. These templates can be discovered and executed with custom parameters, allowing for dynamic text generation based on predefined patterns.
14150 | 
14151 | <Tabs>
14152 |   <Tab title="Sync API">
14153 |     ```java
14154 |     // List available prompt templates
14155 |     var prompts = client.listPrompts();
14156 |     prompts.forEach(prompt -> System.out.println(prompt.getName()));
14157 | 
14158 |     // Execute a prompt template with parameters
14159 |     var response = client.executePrompt("echo", Map.of(
14160 |         "text", "Hello, World!"
14161 |     ));
14162 |     ```
14163 |   </Tab>
14164 | 
14165 |   <Tab title="Async API">
14166 |     ```java
14167 |     // List available prompt templates asynchronously
14168 |     client.listPrompts()
14169 |         .doOnNext(prompts -> prompts.forEach(prompt -> 
14170 |             System.out.println(prompt.getName())))
14171 |         .subscribe();
14172 | 
14173 |     // Execute a prompt template asynchronously
14174 |     client.executePrompt("echo", Map.of(
14175 |             "text", "Hello, World!"
14176 |         ))
14177 |         .subscribe();
14178 |     ```
14179 |   </Tab>
14180 | </Tabs>
14181 | 
14182 | 
14183 | # Overview
14184 | Source: https://modelcontextprotocol.io/sdk/java/mcp-overview
14185 | 
14186 | Introduction to the Model Context Protocol (MCP) Java SDK
14187 | 
14188 | Java SDK for the [Model Context Protocol](https://modelcontextprotocol.org/docs/concepts/architecture)
14189 | enables standardized integration between AI models and tools.
14190 | 
14191 | ## Features
14192 | 
14193 | * MCP Client and MCP Server implementations supporting:
14194 |   * Protocol [version compatibility negotiation](https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization)
14195 |   * [Tool](https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/) discovery, execution, list change notifications
14196 |   * [Resource](https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/) management with URI templates
14197 |   * [Roots](https://spec.modelcontextprotocol.io/specification/2024-11-05/client/roots/) list management and notifications
14198 |   * [Prompt](https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/) handling and management
14199 |   * [Sampling](https://spec.modelcontextprotocol.io/specification/2024-11-05/client/sampling/) support for AI model interactions
14200 | * Multiple transport implementations:
14201 |   * Default transports:
14202 |     * Stdio-based transport for process-based communication
14203 |     * Java HttpClient-based SSE client transport for HTTP SSE Client-side streaming
14204 |     * Servlet-based SSE server transport for HTTP SSE Server streaming
14205 |   * Spring-based transports:
14206 |     * WebFlux SSE client and server transports for reactive HTTP streaming
14207 |     * WebMVC SSE transport for servlet-based HTTP streaming
14208 | * Supports Synchronous and Asynchronous programming paradigms
14209 | 
14210 | ## Architecture
14211 | 
14212 | The SDK follows a layered architecture with clear separation of concerns:
14213 | 
14214 | ![MCP Stack Architecture](https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/java/mcp-stack.svg)
14215 | 
14216 | * **Client/Server Layer (McpClient/McpServer)**: Both use McpSession for sync/async operations,
14217 |   with McpClient handling client-side protocol operations and McpServer managing server-side protocol operations.
14218 | * **Session Layer (McpSession)**: Manages communication patterns and state using DefaultMcpSession implementation.
14219 | * **Transport Layer (McpTransport)**: Handles JSON-RPC message serialization/deserialization via:
14220 |   * StdioTransport (stdin/stdout) in the core module
14221 |   * HTTP SSE transports in dedicated transport modules (Java HttpClient, Spring WebFlux, Spring WebMVC)
14222 | 
14223 | The MCP Client is a key component in the Model Context Protocol (MCP) architecture, responsible for establishing and managing connections with MCP servers.
14224 | It implements the client-side of the protocol.
14225 | 
14226 | ![Java MCP Client Architecture](https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/java/java-mcp-client-architecture.jpg)
14227 | 
14228 | The MCP Server is a foundational component in the Model Context Protocol (MCP) architecture that provides tools, resources, and capabilities to clients.
14229 | It implements the server-side of the protocol.
14230 | 
14231 | ![Java MCP Server Architecture](https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/java/java-mcp-server-architecture.jpg)
14232 | 
14233 | Key Interactions:
14234 | 
14235 | * **Client/Server Initialization**: Transport setup, protocol compatibility check, capability negotiation, and implementation details exchange.
14236 | * **Message Flow**: JSON-RPC message handling with validation, type-safe response processing, and error handling.
14237 | * **Resource Management**: Resource discovery, URI template-based access, subscription system, and content retrieval.
14238 | 
14239 | ## Dependencies
14240 | 
14241 | Add the following Maven dependency to your project:
14242 | 
14243 | <Tabs>
14244 |   <Tab title="Maven">
14245 |     The core MCP functionality:
14246 | 
14247 |     ```xml
14248 |     <dependency>
14249 |         <groupId>io.modelcontextprotocol.sdk</groupId>
14250 |         <artifactId>mcp</artifactId>
14251 |     </dependency>
14252 |     ```
14253 | 
14254 |     For HTTP SSE transport implementations, add one of the following dependencies:
14255 | 
14256 |     ```xml
14257 |     <!-- Spring WebFlux-based SSE client and server transport -->
14258 |     <dependency>
14259 |         <groupId>io.modelcontextprotocol.sdk</groupId>
14260 |         <artifactId>mcp-spring-webflux</artifactId>
14261 |     </dependency>
14262 | 
14263 |     <!-- Spring WebMVC-based SSE server transport -->
14264 |     <dependency>
14265 |         <groupId>io.modelcontextprotocol.sdk</groupId>
14266 |         <artifactId>mcp-spring-webmvc</artifactId>
14267 |     </dependency>
14268 |     ```
14269 |   </Tab>
14270 | 
14271 |   <Tab title="Gradle">
14272 |     The core MCP functionality:
14273 | 
14274 |     ```groovy
14275 |     dependencies {
14276 |       implementation platform("io.modelcontextprotocol.sdk:mcp")
14277 |       //...
14278 |     }
14279 |     ```
14280 | 
14281 |     For HTTP SSE transport implementations, add one of the following dependencies:
14282 | 
14283 |     ```groovy
14284 |     // Spring WebFlux-based SSE client and server transport
14285 |     dependencies {
14286 |       implementation platform("io.modelcontextprotocol.sdk:mcp-spring-webflux")
14287 |     }
14288 | 
14289 |     // Spring WebMVC-based SSE server transport
14290 |     dependencies {
14291 |       implementation platform("io.modelcontextprotocol.sdk:mcp-spring-webmvc")
14292 |     }
14293 |     ```
14294 |   </Tab>
14295 | </Tabs>
14296 | 
14297 | ### Bill of Materials (BOM)
14298 | 
14299 | The Bill of Materials (BOM) declares the recommended versions of all the dependencies used by a given release.
14300 | Using the BOM from your application's build script avoids the need for you to specify and maintain the dependency versions yourself.
14301 | Instead, the version of the BOM you're using determines the utilized dependency versions.
14302 | It also ensures that you're using supported and tested versions of the dependencies by default, unless you choose to override them.
14303 | 
14304 | Add the BOM to your project:
14305 | 
14306 | <Tabs>
14307 |   <Tab title="Maven">
14308 |     ```xml
14309 |     <dependencyManagement>
14310 |         <dependencies>
14311 |             <dependency>
14312 |                 <groupId>io.modelcontextprotocol.sdk</groupId>
14313 |                 <artifactId>mcp-bom</artifactId>
14314 |                 <version>0.7.0</version>
14315 |                 <type>pom</type>
14316 |                 <scope>import</scope>
14317 |             </dependency>
14318 |         </dependencies>
14319 |     </dependencyManagement>
14320 |     ```
14321 |   </Tab>
14322 | 
14323 |   <Tab title="Gradle">
14324 |     ```groovy
14325 |     dependencies {
14326 |       implementation platform("io.modelcontextprotocol.sdk:mcp-bom:0.7.0")
14327 |       //...
14328 |     }
14329 |     ```
14330 | 
14331 |     Gradle users can also use the Spring AI MCP BOM by leveraging Gradle (5.0+) native support for declaring dependency constraints using a Maven BOM.
14332 |     This is implemented by adding a 'platform' dependency handler method to the dependencies section of your Gradle build script.
14333 |     As shown in the snippet above this can then be followed by version-less declarations of the Starter Dependencies for the one or more spring-ai modules you wish to use, e.g. spring-ai-openai.
14334 |   </Tab>
14335 | </Tabs>
14336 | 
14337 | Replace the version number with the version of the BOM you want to use.
14338 | 
14339 | ### Available Dependencies
14340 | 
14341 | The following dependencies are available and managed by the BOM:
14342 | 
14343 | * Core Dependencies
14344 |   * `io.modelcontextprotocol.sdk:mcp` - Core MCP library providing the base functionality and APIs for Model Context Protocol implementation.
14345 | * Transport Dependencies
14346 |   * `io.modelcontextprotocol.sdk:mcp-spring-webflux` - WebFlux-based Server-Sent Events (SSE) transport implementation for reactive applications.
14347 |   * `io.modelcontextprotocol.sdk:mcp-spring-webmvc` - WebMVC-based Server-Sent Events (SSE) transport implementation for servlet-based applications.
14348 | * Testing Dependencies
14349 |   * `io.modelcontextprotocol.sdk:mcp-test` - Testing utilities and support for MCP-based applications.
14350 | 
14351 | 
14352 | # MCP Server
14353 | Source: https://modelcontextprotocol.io/sdk/java/mcp-server
14354 | 
14355 | Learn how to implement and configure a Model Context Protocol (MCP) server
14356 | 
14357 | ## Overview
14358 | 
14359 | The MCP Server is a foundational component in the Model Context Protocol (MCP) architecture that provides tools, resources, and capabilities to clients. It implements the server-side of the protocol, responsible for:
14360 | 
14361 | * Exposing tools that clients can discover and execute
14362 | * Managing resources with URI-based access patterns
14363 | * Providing prompt templates and handling prompt requests
14364 | * Supporting capability negotiation with clients
14365 | * Implementing server-side protocol operations
14366 | * Managing concurrent client connections
14367 | * Providing structured logging and notifications
14368 | 
14369 | The server supports both synchronous and asynchronous APIs, allowing for flexible integration in different application contexts.
14370 | 
14371 | <Tabs>
14372 |   <Tab title="Sync API">
14373 |     ```java
14374 |     // Create a server with custom configuration
14375 |     McpSyncServer syncServer = McpServer.sync(transport)
14376 |         .serverInfo("my-server", "1.0.0")
14377 |         .capabilities(ServerCapabilities.builder()
14378 |             .resources(true)     // Enable resource support
14379 |             .tools(true)         // Enable tool support
14380 |             .prompts(true)       // Enable prompt support
14381 |             .logging()           // Enable logging support
14382 |             .build())
14383 |         .build();
14384 | 
14385 |     // Register tools, resources, and prompts
14386 |     syncServer.addTool(syncToolRegistration);
14387 |     syncServer.addResource(syncResourceRegistration);
14388 |     syncServer.addPrompt(syncPromptRegistration);
14389 | 
14390 |     // Send logging notifications
14391 |     syncServer.loggingNotification(LoggingMessageNotification.builder()
14392 |         .level(LoggingLevel.INFO)
14393 |         .logger("custom-logger")
14394 |         .data("Server initialized")
14395 |         .build());
14396 | 
14397 |     // Close the server when done
14398 |     syncServer.close();
14399 |     ```
14400 |   </Tab>
14401 | 
14402 |   <Tab title="Async API">
14403 |     ```java
14404 |     // Create an async server with custom configuration
14405 |     McpAsyncServer asyncServer = McpServer.async(transport)
14406 |         .serverInfo("my-server", "1.0.0")
14407 |         .capabilities(ServerCapabilities.builder()
14408 |             .resources(true)     // Enable resource support
14409 |             .tools(true)         // Enable tool support
14410 |             .prompts(true)       // Enable prompt support
14411 |             .logging()           // Enable logging support
14412 |             .build())
14413 |         .build();
14414 | 
14415 |     // Register tools, resources, and prompts
14416 |     asyncServer.addTool(asyncToolRegistration)
14417 |         .doOnSuccess(v -> logger.info("Tool registered"))
14418 |         .subscribe();
14419 | 
14420 |     asyncServer.addResource(asyncResourceRegistration)
14421 |         .doOnSuccess(v -> logger.info("Resource registered"))
14422 |         .subscribe();
14423 | 
14424 |     asyncServer.addPrompt(asyncPromptRegistration)
14425 |         .doOnSuccess(v -> logger.info("Prompt registered"))
14426 |         .subscribe();
14427 | 
14428 |     // Send logging notifications
14429 |     asyncServer.loggingNotification(LoggingMessageNotification.builder()
14430 |         .level(LoggingLevel.INFO)
14431 |         .logger("custom-logger")
14432 |         .data("Server initialized")
14433 |         .build());
14434 | 
14435 |     // Close the server when done
14436 |     asyncServer.close()
14437 |         .doOnSuccess(v -> logger.info("Server closed"))
14438 |         .subscribe();
14439 |     ```
14440 |   </Tab>
14441 | </Tabs>
14442 | 
14443 | ## Server Transport
14444 | 
14445 | The transport layer in the MCP SDK is responsible for handling the communication between clients and servers. It provides different implementations to support various communication protocols and patterns. The SDK includes several built-in transport implementations:
14446 | 
14447 | <Tabs>
14448 |   <Tab title="STDIO">
14449 |     <>
14450 |       Create in-process based transport:
14451 | 
14452 |       ```java
14453 |       StdioServerTransport transport = new StdioServerTransport(new ObjectMapper());
14454 |       ```
14455 | 
14456 |       Provides bidirectional JSON-RPC message handling over standard input/output streams with non-blocking message processing, serialization/deserialization, and graceful shutdown support.
14457 | 
14458 |       Key features:
14459 | 
14460 |       <ul>
14461 |         <li>Bidirectional communication through stdin/stdout</li>
14462 |         <li>Process-based integration support</li>
14463 |         <li>Simple setup and configuration</li>
14464 |         <li>Lightweight implementation</li>
14465 |       </ul>
14466 |     </>
14467 |   </Tab>
14468 | 
14469 |   <Tab title="SSE (WebFlux)">
14470 |     <>
14471 |       <p>Creates WebFlux-based SSE server transport.<br />Requires the <code>mcp-spring-webflux</code> dependency.</p>
14472 | 
14473 |       ```java
14474 |       @Configuration
14475 |       class McpConfig {
14476 |           @Bean
14477 |           WebFluxSseServerTransport webFluxSseServerTransport(ObjectMapper mapper) {
14478 |               return new WebFluxSseServerTransport(mapper, "/mcp/message");
14479 |           }
14480 | 
14481 |           @Bean
14482 |           RouterFunction<?> mcpRouterFunction(WebFluxSseServerTransport transport) {
14483 |               return transport.getRouterFunction();
14484 |           }
14485 |       }
14486 |       ```
14487 | 
14488 |       <p>Implements the MCP HTTP with SSE transport specification, providing:</p>
14489 | 
14490 |       <ul>
14491 |         <li>Reactive HTTP streaming with WebFlux</li>
14492 |         <li>Concurrent client connections through SSE endpoints</li>
14493 |         <li>Message routing and session management</li>
14494 |         <li>Graceful shutdown capabilities</li>
14495 |       </ul>
14496 |     </>
14497 |   </Tab>
14498 | 
14499 |   <Tab title="SSE (WebMvc)">
14500 |     <>
14501 |       <p>Creates WebMvc-based SSE server transport.<br />Requires the <code>mcp-spring-webmvc</code> dependency.</p>
14502 | 
14503 |       ```java
14504 |       @Configuration
14505 |       @EnableWebMvc
14506 |       class McpConfig {
14507 |           @Bean
14508 |           WebMvcSseServerTransport webMvcSseServerTransport(ObjectMapper mapper) {
14509 |               return new WebMvcSseServerTransport(mapper, "/mcp/message");
14510 |           }
14511 | 
14512 |           @Bean
14513 |           RouterFunction<ServerResponse> mcpRouterFunction(WebMvcSseServerTransport transport) {
14514 |               return transport.getRouterFunction();
14515 |           }
14516 |       }
14517 |       ```
14518 | 
14519 |       <p>Implements the MCP HTTP with SSE transport specification, providing:</p>
14520 | 
14521 |       <ul>
14522 |         <li>Server-side event streaming</li>
14523 |         <li>Integration with Spring WebMVC</li>
14524 |         <li>Support for traditional web applications</li>
14525 |         <li>Synchronous operation handling</li>
14526 |       </ul>
14527 |     </>
14528 |   </Tab>
14529 | 
14530 |   <Tab title="SSE (Servlet)">
14531 |     <>
14532 |       <p>
14533 |         Creates a Servlet-based SSE server transport. It is included in the core <code>mcp</code> module.<br />
14534 |         The <code>HttpServletSseServerTransport</code> can be used with any Servlet container.<br />
14535 |         To use it with a Spring Web application, you can register it as a Servlet bean:
14536 |       </p>
14537 | 
14538 |       ```java
14539 |       @Configuration
14540 |       @EnableWebMvc
14541 |       public class McpServerConfig implements WebMvcConfigurer {
14542 | 
14543 |           @Bean
14544 |           public HttpServletSseServerTransport servletSseServerTransport() {
14545 |               return new HttpServletSseServerTransport(new ObjectMapper(), "/mcp/message");
14546 |           }
14547 | 
14548 |           @Bean
14549 |           public ServletRegistrationBean customServletBean(HttpServletSseServerTransport servlet) {
14550 |               return new ServletRegistrationBean(servlet);
14551 |           }
14552 |       }
14553 |       ```
14554 | 
14555 |       <p>
14556 |         Implements the MCP HTTP with SSE transport specification using the traditional Servlet API, providing:
14557 |       </p>
14558 | 
14559 |       <ul>
14560 |         <li>Asynchronous message handling using Servlet 6.0 async support</li>
14561 |         <li>Session management for multiple client connections</li>
14562 | 
14563 |         <li>
14564 |           Two types of endpoints:
14565 | 
14566 |           <ul>
14567 |             <li>SSE endpoint (<code>/sse</code>) for server-to-client events</li>
14568 |             <li>Message endpoint (configurable) for client-to-server requests</li>
14569 |           </ul>
14570 |         </li>
14571 | 
14572 |         <li>Error handling and response formatting</li>
14573 |         <li>Graceful shutdown support</li>
14574 |       </ul>
14575 |     </>
14576 |   </Tab>
14577 | </Tabs>
14578 | 
14579 | ## Server Capabilities
14580 | 
14581 | The server can be configured with various capabilities:
14582 | 
14583 | ```java
14584 | var capabilities = ServerCapabilities.builder()
14585 |     .resources(false, true)  // Resource support with list changes notifications
14586 |     .tools(true)            // Tool support with list changes notifications
14587 |     .prompts(true)          // Prompt support with list changes notifications
14588 |     .logging()              // Enable logging support (enabled by default with loging level INFO)
14589 |     .build();
14590 | ```
14591 | 
14592 | ### Logging Support
14593 | 
14594 | The server provides structured logging capabilities that allow sending log messages to clients with different severity levels:
14595 | 
14596 | ```java
14597 | // Send a log message to clients
14598 | server.loggingNotification(LoggingMessageNotification.builder()
14599 |     .level(LoggingLevel.INFO)
14600 |     .logger("custom-logger")
14601 |     .data("Custom log message")
14602 |     .build());
14603 | ```
14604 | 
14605 | Clients can control the minimum logging level they receive through the `mcpClient.setLoggingLevel(level)` request. Messages below the set level will be filtered out.
14606 | Supported logging levels (in order of increasing severity): DEBUG (0), INFO (1), NOTICE (2), WARNING (3), ERROR (4), CRITICAL (5), ALERT (6), EMERGENCY (7)
14607 | 
14608 | ### Tool Registration
14609 | 
14610 | <Tabs>
14611 |   <Tab title="Sync">
14612 |     ```java
14613 |     // Sync tool registration
14614 |     var schema = """
14615 |                 {
14616 |                   "type" : "object",
14617 |                   "id" : "urn:jsonschema:Operation",
14618 |                   "properties" : {
14619 |                     "operation" : {
14620 |                       "type" : "string"
14621 |                     },
14622 |                     "a" : {
14623 |                       "type" : "number"
14624 |                     },
14625 |                     "b" : {
14626 |                       "type" : "number"
14627 |                     }
14628 |                   }
14629 |                 }
14630 |                 """;
14631 |     var syncToolRegistration = new McpServerFeatures.SyncToolRegistration(
14632 |         new Tool("calculator", "Basic calculator", schema),
14633 |         arguments -> {
14634 |             // Tool implementation
14635 |             return new CallToolResult(result, false);
14636 |         }
14637 |     );
14638 |     ```
14639 |   </Tab>
14640 | 
14641 |   <Tab title="Async">
14642 |     ```java
14643 |     // Async tool registration
14644 |     var schema = """
14645 |                 {
14646 |                   "type" : "object",
14647 |                   "id" : "urn:jsonschema:Operation",
14648 |                   "properties" : {
14649 |                     "operation" : {
14650 |                       "type" : "string"
14651 |                     },
14652 |                     "a" : {
14653 |                       "type" : "number"
14654 |                     },
14655 |                     "b" : {
14656 |                       "type" : "number"
14657 |                     }
14658 |                   }
14659 |                 }
14660 |                 """;
14661 |     var asyncToolRegistration = new McpServerFeatures.AsyncToolRegistration(
14662 |         new Tool("calculator", "Basic calculator", schema),
14663 |         arguments -> {
14664 |             // Tool implementation
14665 |             return Mono.just(new CallToolResult(result, false));
14666 |         }
14667 |     );
14668 |     ```
14669 |   </Tab>
14670 | </Tabs>
14671 | 
14672 | ### Resource Registration
14673 | 
14674 | <Tabs>
14675 |   <Tab title="Sync">
14676 |     ```java
14677 |     // Sync resource registration
14678 |     var syncResourceRegistration = new McpServerFeatures.SyncResourceRegistration(
14679 |         new Resource("custom://resource", "name", "description", "mime-type", null),
14680 |         request -> {
14681 |             // Resource read implementation
14682 |             return new ReadResourceResult(contents);
14683 |         }
14684 |     );
14685 |     ```
14686 |   </Tab>
14687 | 
14688 |   <Tab title="Async">
14689 |     ```java
14690 |     // Async resource registration
14691 |     var asyncResourceRegistration = new McpServerFeatures.AsyncResourceRegistration(
14692 |         new Resource("custom://resource", "name", "description", "mime-type", null),
14693 |         request -> {
14694 |             // Resource read implementation
14695 |             return Mono.just(new ReadResourceResult(contents));
14696 |         }
14697 |     );
14698 |     ```
14699 |   </Tab>
14700 | </Tabs>
14701 | 
14702 | ### Prompt Registration
14703 | 
14704 | <Tabs>
14705 |   <Tab title="Sync">
14706 |     ```java
14707 |     // Sync prompt registration
14708 |     var syncPromptRegistration = new McpServerFeatures.SyncPromptRegistration(
14709 |         new Prompt("greeting", "description", List.of(
14710 |             new PromptArgument("name", "description", true)
14711 |         )),
14712 |         request -> {
14713 |             // Prompt implementation
14714 |             return new GetPromptResult(description, messages);
14715 |         }
14716 |     );
14717 |     ```
14718 |   </Tab>
14719 | 
14720 |   <Tab title="Async">
14721 |     ```java
14722 |     // Async prompt registration
14723 |     var asyncPromptRegistration = new McpServerFeatures.AsyncPromptRegistration(
14724 |         new Prompt("greeting", "description", List.of(
14725 |             new PromptArgument("name", "description", true)
14726 |         )),
14727 |         request -> {
14728 |             // Prompt implementation
14729 |             return Mono.just(new GetPromptResult(description, messages));
14730 |         }
14731 |     );
14732 |     ```
14733 |   </Tab>
14734 | </Tabs>
14735 | 
14736 | ## Error Handling
14737 | 
14738 | The SDK provides comprehensive error handling through the McpError class, covering protocol compatibility, transport communication, JSON-RPC messaging, tool execution, resource management, prompt handling, timeouts, and connection issues. This unified error handling approach ensures consistent and reliable error management across both synchronous and asynchronous operations.
14739 | 
14740 | 
14741 | # Building MCP with LLMs
14742 | Source: https://modelcontextprotocol.io/tutorials/building-mcp-with-llms
14743 | 
14744 | Speed up your MCP development using LLMs such as Claude!
14745 | 
14746 | This guide will help you use LLMs to help you build custom Model Context Protocol (MCP) servers and clients. We'll be focusing on Claude for this tutorial, but you can do this with any frontier LLM.
14747 | 
14748 | ## Preparing the documentation
14749 | 
14750 | Before starting, gather the necessary documentation to help Claude understand MCP:
14751 | 
14752 | 1.  Visit [https://modelcontextprotocol.io/llms-full.txt](https://modelcontextprotocol.io/llms-full.txt) and copy the full documentation text
14753 | 2.  Navigate to either the [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) or [Python SDK repository](https://github.com/modelcontextprotocol/python-sdk)
14754 | 3.  Copy the README files and other relevant documentation
14755 | 4.  Paste these documents into your conversation with Claude
14756 | 
14757 | ## Describing your server
14758 | 
14759 | Once you've provided the documentation, clearly describe to Claude what kind of server you want to build. Be specific about:
14760 | 
14761 | *   What resources your server will expose
14762 | *   What tools it will provide
14763 | *   Any prompts it should offer
14764 | *   What external systems it needs to interact with
14765 | 
14766 | For example:
14767 | 
14768 | ```
14769 | Build an MCP server that:
14770 | - Connects to my company's PostgreSQL database
14771 | - Exposes table schemas as resources
14772 | - Provides tools for running read-only SQL queries
14773 | - Includes prompts for common data analysis tasks
14774 | ```
14775 | 
14776 | ## Working with Claude
14777 | 
14778 | When working with Claude on MCP servers:
14779 | 
14780 | 1.  Start with the core functionality first, then iterate to add more features
14781 | 2.  Ask Claude to explain any parts of the code you don't understand
14782 | 3.  Request modifications or improvements as needed
14783 | 4.  Have Claude help you test the server and handle edge cases
14784 | 
14785 | Claude can help implement all the key MCP features:
14786 | 
14787 | *   Resource management and exposure
14788 | *   Tool definitions and implementations
14789 | *   Prompt templates and handlers
14790 | *   Error handling and logging
14791 | *   Connection and transport setup
14792 | 
14793 | ## Best practices
14794 | 
14795 | When building MCP servers with Claude:
14796 | 
14797 | *   Break down complex servers into smaller pieces
14798 | *   Test each component thoroughly before moving on
14799 | *   Keep security in mind - validate inputs and limit access appropriately
14800 | *   Document your code well for future maintenance
14801 | *   Follow MCP protocol specifications carefully
14802 | 
14803 | ## Next steps
14804 | 
14805 | After Claude helps you build your server:
14806 | 
14807 | 1.  Review the generated code carefully
14808 | 2.  Test the server with the MCP Inspector tool
14809 | 3.  Connect it to Claude.app or other MCP clients
14810 | 4.  Iterate based on real usage and feedback
14811 | 
14812 | Remember that Claude can help you modify and improve your server as requirements change over time.
14813 | 
14814 | Need more guidance? Just ask Claude specific questions about implementing MCP features or troubleshooting issues that arise.
14815 | 
14816 | ================
14817 | File: MCP-Typescript-readme.txt
14818 | ================
14819 | MCP TypeScript SDK NPM Version MIT licensed
14820 | Table of Contents
14821 | Overview
14822 | Installation
14823 | Quickstart
14824 | What is MCP?
14825 | Core Concepts
14826 | Server
14827 | Resources
14828 | Tools
14829 | Prompts
14830 | Running Your Server
14831 | stdio
14832 | HTTP with SSE
14833 | Testing and Debugging
14834 | Examples
14835 | Echo Server
14836 | SQLite Explorer
14837 | Advanced Usage
14838 | Low-Level Server
14839 | Writing MCP Clients
14840 | Server Capabilities
14841 | Overview
14842 | The Model Context Protocol allows applications to provide context for LLMs in a standardized way, separating the concerns of providing context from the actual LLM interaction. This TypeScript SDK implements the full MCP specification, making it easy to:
14843 | 
14844 | Build MCP clients that can connect to any MCP server
14845 | Create MCP servers that expose resources, prompts and tools
14846 | Use standard transports like stdio and SSE
14847 | Handle all MCP protocol messages and lifecycle events
14848 | Installation
14849 | npm install @modelcontextprotocol/sdk
14850 | Quick Start
14851 | Let's create a simple MCP server that exposes a calculator tool and some data:
14852 | 
14853 | import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
14854 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
14855 | import { z } from "zod";
14856 | 
14857 | // Create an MCP server
14858 | const server = new McpServer({
14859 |   name: "Demo",
14860 |   version: "1.0.0"
14861 | });
14862 | 
14863 | // Add an addition tool
14864 | server.tool("add",
14865 |   { a: z.number(), b: z.number() },
14866 |   async ({ a, b }) => ({
14867 |     content: [{ type: "text", text: String(a + b) }]
14868 |   })
14869 | );
14870 | 
14871 | // Add a dynamic greeting resource
14872 | server.resource(
14873 |   "greeting",
14874 |   new ResourceTemplate("greeting://{name}", { list: undefined }),
14875 |   async (uri, { name }) => ({
14876 |     contents: [{
14877 |       uri: uri.href,
14878 |       text: `Hello, ${name}!`
14879 |     }]
14880 |   })
14881 | );
14882 | 
14883 | // Start receiving messages on stdin and sending messages on stdout
14884 | const transport = new StdioServerTransport();
14885 | await server.connect(transport);
14886 | What is MCP?
14887 | The Model Context Protocol (MCP) lets you build servers that expose data and functionality to LLM applications in a secure, standardized way. Think of it like a web API, but specifically designed for LLM interactions. MCP servers can:
14888 | 
14889 | Expose data through Resources (think of these sort of like GET endpoints; they are used to load information into the LLM's context)
14890 | Provide functionality through Tools (sort of like POST endpoints; they are used to execute code or otherwise produce a side effect)
14891 | Define interaction patterns through Prompts (reusable templates for LLM interactions)
14892 | And more!
14893 | Core Concepts
14894 | Server
14895 | The McpServer is your core interface to the MCP protocol. It handles connection management, protocol compliance, and message routing:
14896 | 
14897 | const server = new McpServer({
14898 |   name: "My App",
14899 |   version: "1.0.0"
14900 | });
14901 | Resources
14902 | Resources are how you expose data to LLMs. They're similar to GET endpoints in a REST API - they provide data but shouldn't perform significant computation or have side effects:
14903 | 
14904 | // Static resource
14905 | server.resource(
14906 |   "config",
14907 |   "config://app",
14908 |   async (uri) => ({
14909 |     contents: [{
14910 |       uri: uri.href,
14911 |       text: "App configuration here"
14912 |     }]
14913 |   })
14914 | );
14915 | 
14916 | // Dynamic resource with parameters
14917 | server.resource(
14918 |   "user-profile",
14919 |   new ResourceTemplate("users://{userId}/profile", { list: undefined }),
14920 |   async (uri, { userId }) => ({
14921 |     contents: [{
14922 |       uri: uri.href,
14923 |       text: `Profile data for user ${userId}`
14924 |     }]
14925 |   })
14926 | );
14927 | Tools
14928 | Tools let LLMs take actions through your server. Unlike resources, tools are expected to perform computation and have side effects:
14929 | 
14930 | // Simple tool with parameters
14931 | server.tool(
14932 |   "calculate-bmi",
14933 |   {
14934 |     weightKg: z.number(),
14935 |     heightM: z.number()
14936 |   },
14937 |   async ({ weightKg, heightM }) => ({
14938 |     content: [{
14939 |       type: "text",
14940 |       text: String(weightKg / (heightM * heightM))
14941 |     }]
14942 |   })
14943 | );
14944 | 
14945 | // Async tool with external API call
14946 | server.tool(
14947 |   "fetch-weather",
14948 |   { city: z.string() },
14949 |   async ({ city }) => {
14950 |     const response = await fetch(`https://api.weather.com/${city}`);
14951 |     const data = await response.text();
14952 |     return {
14953 |       content: [{ type: "text", text: data }]
14954 |     };
14955 |   }
14956 | );
14957 | Prompts
14958 | Prompts are reusable templates that help LLMs interact with your server effectively:
14959 | 
14960 | server.prompt(
14961 |   "review-code",
14962 |   { code: z.string() },
14963 |   ({ code }) => ({
14964 |     messages: [{
14965 |       role: "user",
14966 |       content: {
14967 |         type: "text",
14968 |         text: `Please review this code:\n\n${code}`
14969 |       }
14970 |     }]
14971 |   })
14972 | );
14973 | Running Your Server
14974 | MCP servers in TypeScript need to be connected to a transport to communicate with clients. How you start the server depends on the choice of transport:
14975 | 
14976 | stdio
14977 | For command-line tools and direct integrations:
14978 | 
14979 | import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
14980 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
14981 | 
14982 | const server = new McpServer({
14983 |   name: "example-server",
14984 |   version: "1.0.0"
14985 | });
14986 | 
14987 | // ... set up server resources, tools, and prompts ...
14988 | 
14989 | const transport = new StdioServerTransport();
14990 | await server.connect(transport);
14991 | HTTP with SSE
14992 | For remote servers, start a web server with a Server-Sent Events (SSE) endpoint, and a separate endpoint for the client to send its messages to:
14993 | 
14994 | import express from "express";
14995 | import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
14996 | import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
14997 | 
14998 | const server = new McpServer({
14999 |   name: "example-server",
15000 |   version: "1.0.0"
15001 | });
15002 | 
15003 | // ... set up server resources, tools, and prompts ...
15004 | 
15005 | const app = express();
15006 | 
15007 | app.get("/sse", async (req, res) => {
15008 |   const transport = new SSEServerTransport("/messages", res);
15009 |   await server.connect(transport);
15010 | });
15011 | 
15012 | app.post("/messages", async (req, res) => {
15013 |   // Note: to support multiple simultaneous connections, these messages will
15014 |   // need to be routed to a specific matching transport. (This logic isn't
15015 |   // implemented here, for simplicity.)
15016 |   await transport.handlePostMessage(req, res);
15017 | });
15018 | 
15019 | app.listen(3001);
15020 | Testing and Debugging
15021 | To test your server, you can use the MCP Inspector. See its README for more information.
15022 | 
15023 | Examples
15024 | Echo Server
15025 | A simple server demonstrating resources, tools, and prompts:
15026 | 
15027 | import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
15028 | import { z } from "zod";
15029 | 
15030 | const server = new McpServer({
15031 |   name: "Echo",
15032 |   version: "1.0.0"
15033 | });
15034 | 
15035 | server.resource(
15036 |   "echo",
15037 |   new ResourceTemplate("echo://{message}", { list: undefined }),
15038 |   async (uri, { message }) => ({
15039 |     contents: [{
15040 |       uri: uri.href,
15041 |       text: `Resource echo: ${message}`
15042 |     }]
15043 |   })
15044 | );
15045 | 
15046 | server.tool(
15047 |   "echo",
15048 |   { message: z.string() },
15049 |   async ({ message }) => ({
15050 |     content: [{ type: "text", text: `Tool echo: ${message}` }]
15051 |   })
15052 | );
15053 | 
15054 | server.prompt(
15055 |   "echo",
15056 |   { message: z.string() },
15057 |   ({ message }) => ({
15058 |     messages: [{
15059 |       role: "user",
15060 |       content: {
15061 |         type: "text",
15062 |         text: `Please process this message: ${message}`
15063 |       }
15064 |     }]
15065 |   })
15066 | );
15067 | SQLite Explorer
15068 | A more complex example showing database integration:
15069 | 
15070 | import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
15071 | import sqlite3 from "sqlite3";
15072 | import { promisify } from "util";
15073 | import { z } from "zod";
15074 | 
15075 | const server = new McpServer({
15076 |   name: "SQLite Explorer",
15077 |   version: "1.0.0"
15078 | });
15079 | 
15080 | // Helper to create DB connection
15081 | const getDb = () => {
15082 |   const db = new sqlite3.Database("database.db");
15083 |   return {
15084 |     all: promisify<string, any[]>(db.all.bind(db)),
15085 |     close: promisify(db.close.bind(db))
15086 |   };
15087 | };
15088 | 
15089 | server.resource(
15090 |   "schema",
15091 |   "schema://main",
15092 |   async (uri) => {
15093 |     const db = getDb();
15094 |     try {
15095 |       const tables = await db.all(
15096 |         "SELECT sql FROM sqlite_master WHERE type='table'"
15097 |       );
15098 |       return {
15099 |         contents: [{
15100 |           uri: uri.href,
15101 |           text: tables.map((t: {sql: string}) => t.sql).join("\n")
15102 |         }]
15103 |       };
15104 |     } finally {
15105 |       await db.close();
15106 |     }
15107 |   }
15108 | );
15109 | 
15110 | server.tool(
15111 |   "query",
15112 |   { sql: z.string() },
15113 |   async ({ sql }) => {
15114 |     const db = getDb();
15115 |     try {
15116 |       const results = await db.all(sql);
15117 |       return {
15118 |         content: [{
15119 |           type: "text",
15120 |           text: JSON.stringify(results, null, 2)
15121 |         }]
15122 |       };
15123 |     } catch (err: unknown) {
15124 |       const error = err as Error;
15125 |       return {
15126 |         content: [{
15127 |           type: "text",
15128 |           text: `Error: ${error.message}`
15129 |         }],
15130 |         isError: true
15131 |       };
15132 |     } finally {
15133 |       await db.close();
15134 |     }
15135 |   }
15136 | );
15137 | Advanced Usage
15138 | Low-Level Server
15139 | For more control, you can use the low-level Server class directly:
15140 | 
15141 | import { Server } from "@modelcontextprotocol/sdk/server/index.js";
15142 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
15143 | import {
15144 |   ListPromptsRequestSchema,
15145 |   GetPromptRequestSchema
15146 | } from "@modelcontextprotocol/sdk/types.js";
15147 | 
15148 | const server = new Server(
15149 |   {
15150 |     name: "example-server",
15151 |     version: "1.0.0"
15152 |   },
15153 |   {
15154 |     capabilities: {
15155 |       prompts: {}
15156 |     }
15157 |   }
15158 | );
15159 | 
15160 | server.setRequestHandler(ListPromptsRequestSchema, async () => {
15161 |   return {
15162 |     prompts: [{
15163 |       name: "example-prompt",
15164 |       description: "An example prompt template",
15165 |       arguments: [{
15166 |         name: "arg1",
15167 |         description: "Example argument",
15168 |         required: true
15169 |       }]
15170 |     }]
15171 |   };
15172 | });
15173 | 
15174 | server.setRequestHandler(GetPromptRequestSchema, async (request) => {
15175 |   if (request.params.name !== "example-prompt") {
15176 |     throw new Error("Unknown prompt");
15177 |   }
15178 |   return {
15179 |     description: "Example prompt",
15180 |     messages: [{
15181 |       role: "user",
15182 |       content: {
15183 |         type: "text",
15184 |         text: "Example prompt text"
15185 |       }
15186 |     }]
15187 |   };
15188 | });
15189 | 
15190 | const transport = new StdioServerTransport();
15191 | await server.connect(transport);
15192 | Writing MCP Clients
15193 | The SDK provides a high-level client interface:
15194 | 
15195 | import { Client } from "@modelcontextprotocol/sdk/client/index.js";
15196 | import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
15197 | 
15198 | const transport = new StdioClientTransport({
15199 |   command: "node",
15200 |   args: ["server.js"]
15201 | });
15202 | 
15203 | const client = new Client(
15204 |   {
15205 |     name: "example-client",
15206 |     version: "1.0.0"
15207 |   },
15208 |   {
15209 |     capabilities: {
15210 |       prompts: {},
15211 |       resources: {},
15212 |       tools: {}
15213 |     }
15214 |   }
15215 | );
15216 | 
15217 | await client.connect(transport);
15218 | 
15219 | // List prompts
15220 | const prompts = await client.listPrompts();
15221 | 
15222 | // Get a prompt
15223 | const prompt = await client.getPrompt("example-prompt", {
15224 |   arg1: "value"
15225 | });
15226 | 
15227 | // List resources
15228 | const resources = await client.listResources();
15229 | 
15230 | // Read a resource
15231 | const resource = await client.readResource("file:///example.txt");
15232 | 
15233 | // Call a tool
15234 | const result = await client.callTool({
15235 |   name: "example-tool",
15236 |   arguments: {
15237 |     arg1: "value"
15238 |   }
15239 | });
15240 | 
15241 | ================
15242 | File: package.json
15243 | ================
15244 | {
15245 |   "name": "vibe-coder-mcp",
15246 |   "version": "0.3.0",
15247 |   "description": "A custom MCP for vibecoding",
15248 |   "private": true,
15249 |   "type": "module",
15250 |   "bin": {
15251 |     "vibe-coder-mcp": "./build/mcp-server.js"
15252 |   },
15253 |   "files": [
15254 |     "build"
15255 |   ],
15256 |   "scripts": {
15257 |     "build": "tsc --project tsconfig.build.json && node -e \"require('fs').chmodSync('build/mcp-server.js', '755')\"",
15258 |     "watch": "tsc --project tsconfig.build.json --watch",
15259 |     "inspector": "npx @modelcontextprotocol/inspector build/mcp-server.js"
15260 |   },
15261 |   "dependencies": {
15262 |     "@modelcontextprotocol/sdk": "1.7.0",
15263 |     "zod": "^3.22.4"
15264 |   },
15265 |   "devDependencies": {
15266 |     "@types/node": "^20.11.24",
15267 |     "typescript": "^5.3.3"
15268 |   }
15269 | }
15270 | 
15271 | ================
15272 | File: README.md
15273 | ================
15274 | # Vibe-Coder MCP Server
15275 | 
15276 | A Model Context Protocol server that implements a structured development workflow for LLM-based coding.
15277 | 
15278 | ## Overview
15279 | 
15280 | This MCP server helps LLMs build features in an organized, clean, and safe manner by providing:
15281 | 
15282 | - A structured feature clarification process with guided questions
15283 | - PRD and implementation plan generation
15284 | - Phased development with task tracking
15285 | - Progress tracking and status reporting
15286 | 
15287 | ## Features
15288 | 
15289 | ### Resources
15290 | - Feature details, PRDs, and implementation plans
15291 | - Progress reports and status tracking
15292 | - Phase and task details
15293 | 
15294 | ### Tools
15295 | - `start_feature_clarification` - Begin the feature clarification process
15296 | - `provide_clarification` - Answer clarification questions about a feature
15297 | - `generate_prd` - Generate a Product Requirements Document and implementation plan
15298 | - `create_phase` - Create a development phase for a feature
15299 | - `add_task` - Add tasks to a development phase
15300 | - `update_phase_status` - Update the status of a phase
15301 | - `update_task_status` - Update the completion status of a task
15302 | - `get_next_phase_action` - Get guidance on what to do next
15303 | 
15304 | ### Prompts
15305 | - `feature-planning` - A prompt template for planning feature development
15306 | 
15307 | ## Development
15308 | 
15309 | Install dependencies:
15310 | ```bash
15311 | npm install
15312 | ```
15313 | 
15314 | Build the server:
15315 | ```bash
15316 | npm run build
15317 | ```
15318 | 
15319 | For development with auto-rebuild:
15320 | ```bash
15321 | npm run watch
15322 | ```
15323 | 
15324 | ## Installation
15325 | 
15326 | To use with compatible MCP clients:
15327 | 
15328 | On MacOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
15329 | On Windows: `%APPDATA%/Claude/claude_desktop_config.json`
15330 | 
15331 | ```json
15332 | {
15333 |   "mcpServers": {
15334 |     "vibe-coder-mcp": {
15335 |       "command": "/path/to/vibe-coder-mcp/build/mcp-server.js"
15336 |     }
15337 |   }
15338 | }
15339 | ```
15340 | 
15341 | ### Debugging
15342 | 
15343 | Since MCP servers communicate over stdio, debugging can be challenging. We recommend using the [MCP Inspector](https://github.com/modelcontextprotocol/inspector), which is available as a package script:
15344 | 
15345 | ```bash
15346 | npm run inspector
15347 | ```
15348 | 
15349 | The Inspector will provide a URL to access debugging tools in your browser.
15350 | 
15351 | ## Implementation Notes
15352 | 
15353 | This server is implemented using the high-level `McpServer` class from the Model Context Protocol TypeScript SDK, which simplifies the process of creating MCP servers by providing a clean API for defining resources, tools, and prompts.
15354 | 
15355 | ```typescript
15356 | import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
15357 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
15358 | 
15359 | // Create an MCP server
15360 | const server = new McpServer({
15361 |   name: "Vibe-Coder",
15362 |   version: "0.3.0"
15363 | });
15364 | 
15365 | // Add a resource
15366 | server.resource(
15367 |   "features-list",
15368 |   "features://list",
15369 |   async (uri) => ({ /* ... */ })
15370 | );
15371 | 
15372 | // Add a tool
15373 | server.tool(
15374 |   "start_feature_clarification",
15375 |   { /* parameters schema */ },
15376 |   async (params) => ({ /* ... */ })
15377 | );
15378 | 
15379 | // Add a prompt
15380 | server.prompt(
15381 |   "feature-planning",
15382 |   { /* parameters schema */ },
15383 |   (params) => ({ /* ... */ })
15384 | );
15385 | 
15386 | // Start the server
15387 | const transport = new StdioServerTransport();
15388 | await server.connect(transport);
15389 | ```
15390 | 
15391 | ## Workflow
15392 | 
15393 | The Vibe-Coder MCP server is designed to guide the development process through the following steps:
15394 | 
15395 | 1. **Feature Clarification**: Start by gathering requirements and understanding the feature's purpose, target users, and constraints
15396 | 2. **Documentation**: Generate a PRD and implementation plan based on the clarified requirements
15397 | 3. **Phased Development**: Break down the implementation into logical phases with clear tasks
15398 | 4. **Progress Tracking**: Monitor the completion of tasks and phases to guide development
15399 | 5. **Completion**: Verify that all requirements have been implemented and the feature is ready for use
15400 | 
15401 | ================
15402 | File: test-mcp.js
15403 | ================
15404 | #!/usr/bin/env node
15405 | 
15406 | import { spawn } from 'child_process';
15407 | import { createInterface } from 'readline';
15408 | 
15409 | console.log('Starting Vibe-Coder MCP server...');
15410 | // Start the MCP server
15411 | const serverProcess = spawn('node', ['./build/index.js']);
15412 | 
15413 | // Create readline interface to read server output
15414 | const rl = createInterface({
15415 |   input: serverProcess.stdout,
15416 |   output: process.stdout,
15417 |   terminal: false
15418 | });
15419 | 
15420 | // Set up error handling
15421 | serverProcess.stderr.on('data', (data) => {
15422 |   console.error(`Server stderr: ${data.toString()}`);
15423 | });
15424 | 
15425 | // Wait for server to start
15426 | setTimeout(() => {
15427 |   console.log('Sending initialize request...');
15428 |   
15429 |   // First, send the initialize request
15430 |   const initializeMsg = {
15431 |     jsonrpc: "2.0",
15432 |     id: "init1",
15433 |     method: "initialize",
15434 |     params: {
15435 |       client: {
15436 |         name: "Test Client",
15437 |         version: "1.0.0"
15438 |       },
15439 |       capabilities: {
15440 |         resources: {},
15441 |         tools: {},
15442 |         prompts: {}
15443 |       }
15444 |     }
15445 |   };
15446 |   
15447 |   serverProcess.stdin.write(JSON.stringify(initializeMsg) + '\n');
15448 |   
15449 |   // Wait for response and send clarification
15450 |   let featureId = null;
15451 |   let questionIndex = 0;
15452 |   
15453 |   rl.on('line', (line) => {
15454 |     try {
15455 |       console.log('Raw server output:', line);
15456 |       const response = JSON.parse(line);
15457 |       console.log('Parsed response:', JSON.stringify(response, null, 2));
15458 |       
15459 |       // After initialization, list available tools
15460 |       if (response.id === "init1") {
15461 |         console.log('Initialization successful, listing tools...');
15462 |         const listToolsMsg = {
15463 |           jsonrpc: "2.0",
15464 |           id: "list1",
15465 |           method: "listTools",
15466 |           params: {}
15467 |         };
15468 |         serverProcess.stdin.write(JSON.stringify(listToolsMsg) + '\n');
15469 |       }
15470 |       
15471 |       // After listing tools, call the start_feature_clarification tool
15472 |       if (response.id === "list1") {
15473 |         console.log('Tools listed, starting feature clarification...');
15474 |         const callToolMsg = {
15475 |           jsonrpc: "2.0",
15476 |           id: "call1",
15477 |           method: "callTool",
15478 |           params: {
15479 |             name: "start_feature_clarification",
15480 |             arguments: {
15481 |               featureName: "Test Automated Feature",
15482 |               initialDescription: "This is a test automated feature for testing the clarification flow"
15483 |             }
15484 |           }
15485 |         };
15486 |         serverProcess.stdin.write(JSON.stringify(callToolMsg) + '\n');
15487 |       }
15488 |       
15489 |       // Check if this is a response to start_feature_clarification
15490 |       if (response.id === "call1" && response.result?.content) {
15491 |         // Extract feature ID from response text
15492 |         const text = response.result.content[0].text;
15493 |         const match = text.match(/Feature ID: ([a-z0-9]+)/);
15494 |         
15495 |         if (match && match[1]) {
15496 |           featureId = match[1];
15497 |           console.log(`Extracted feature ID: ${featureId}`);
15498 |           
15499 |           // Send first clarification
15500 |           sendClarification(featureId, questionIndex, "This is an answer to question 0");
15501 |         }
15502 |       }
15503 |       
15504 |       // Check if this is a response to any of the clarification messages
15505 |       if (response.id && response.id.startsWith("clarify") && response.result?.content) {
15506 |         const text = response.result.content[0].text;
15507 |         console.log('Clarification response text:', text);
15508 |         
15509 |         // Check if we need to send the next question
15510 |         if (text.startsWith("Response recorded.")) {
15511 |           questionIndex++;
15512 |           if (questionIndex < 7) { // We have 7 default questions
15513 |             setTimeout(() => {
15514 |               sendClarification(featureId, questionIndex, `This is an answer to question ${questionIndex}`);
15515 |             }, 500);
15516 |           } else {
15517 |             console.log('All questions answered, test complete');
15518 |             serverProcess.kill();
15519 |             process.exit(0);
15520 |           }
15521 |         }
15522 |       }
15523 |     } catch (e) {
15524 |       console.error('Error parsing JSON response:', e);
15525 |     }
15526 |   });
15527 |   
15528 |   function sendClarification(featureId, index, answer) {
15529 |     const clarifyMsg = {
15530 |       jsonrpc: "2.0",
15531 |       id: `clarify${index}`,
15532 |       method: "callTool",
15533 |       params: {
15534 |         name: "provide_clarification",
15535 |         arguments: {
15536 |           featureId: featureId,
15537 |           question: `Question #${index}`,
15538 |           answer: answer
15539 |         }
15540 |       }
15541 |     };
15542 |     console.log(`Sending clarification ${index}...`);
15543 |     serverProcess.stdin.write(JSON.stringify(clarifyMsg) + '\n');
15544 |   }
15545 | }, 1000);
15546 | 
15547 | // Handle process exit
15548 | process.on('exit', () => {
15549 |   serverProcess.kill();
15550 | });
15551 | 
15552 | ================
15553 | File: tsconfig.build.json
15554 | ================
15555 | {
15556 |   "compilerOptions": {
15557 |     "target": "ES2022",
15558 |     "module": "Node16",
15559 |     "moduleResolution": "Node16",
15560 |     "outDir": "./build",
15561 |     "rootDir": "./src",
15562 |     "strict": true,
15563 |     "esModuleInterop": true,
15564 |     "skipLibCheck": true,
15565 |     "forceConsistentCasingInFileNames": true
15566 |   },
15567 |   "include": ["src/mcp-server.ts", "src/types.ts", "src/storage.ts", "src/utils.ts", "src/clarification.ts", "src/documentation.ts"],
15568 |   "exclude": ["node_modules", "src/registry.ts", "src/resource-handlers.ts", "src/tool-handlers.ts", "src/index.ts", "src/index-updated.ts"]
15569 | }
15570 | 
15571 | ================
15572 | File: tsconfig.json
15573 | ================
15574 | {
15575 |   "compilerOptions": {
15576 |     "target": "ES2022",
15577 |     "module": "Node16",
15578 |     "moduleResolution": "Node16",
15579 |     "outDir": "./build",
15580 |     "rootDir": "./src",
15581 |     "strict": true,
15582 |     "esModuleInterop": true,
15583 |     "skipLibCheck": true,
15584 |     "forceConsistentCasingInFileNames": true
15585 |   },
15586 |   "include": ["src/**/*"],
15587 |   "exclude": ["node_modules"]
15588 | }
15589 | 
```
Page 4/4FirstPrevNextLast