QUICK_REFERENCE.md•5.71 kB
# Quick Reference: index.ts
## File Structure
```
index.ts (458 lines)
├── Imports (lines 1-21)
├── MCPServer Class (lines 23-237)
│ ├── Constructor (lines 38-65)
│ ├── setupHandlers() (lines 67-227)
│ │ ├── Prompt Handlers (lines 80-106)
│ │ └── Tool Handlers (lines 108-227)
│ └── run() (lines 229-237)
├── Cloudflare Workers Export (lines 239-424)
│ └── fetch() Handler (lines 261-424)
│ ├── /health endpoint
│ ├── /mcp endpoint
│ ├── CORS preflight
│ └── Default response
└── Local Testing Bootstrap (lines 426-458)
```
## Key Classes and Functions
### MCPServer Class
**Purpose**: MCP protocol implementation for stdio transport
**Methods**:
- `constructor()` - Initialize server with tools and prompts capabilities
- `setupHandlers()` - Configure all MCP request handlers
- `run()` - Start server with stdio transport
### Cloudflare Workers Export
**Purpose**: HTTP request handling for deployed Worker
**Main Handler**:
- `fetch(request, env, ctx)` - Routes HTTP requests to appropriate endpoints
## Available Capabilities
### Tools (with listChanged support)
| Tool Name | Description | Required Args | Optional Args |
|-----------|-------------|---------------|---------------|
| `get_time` | Returns current server time | None | None |
| `echo` | Echoes back a message | `message` (string) | None |
| `add` | Adds two numbers | `a` (number), `b` (number) | None |
### Prompts (with listChanged support)
Prompts are imported from `prompts.ts`:
- `code_review` - Code review with focus areas
- `explain_concept` - Technical concept explanations
- `debug_helper` - Debugging assistance
- `api_design` - API design guidance
- `refactor_suggestion` - Code refactoring suggestions
See `prompts.ts` for full documentation.
### Resources (with subscribe support)
Resources are imported from `resources.ts`:
| URI | Name | MIME Type | Description |
|-----|------|-----------|-------------|
| `config://server/info` | Server Information | application/json | Server metadata |
| `config://server/status` | Server Status | application/json | Current status & metrics |
| `docs://mcp/getting-started` | Getting Started | text/markdown | Usage guide |
**Resource Templates**:
- `log://{level}/{message}` - Parameterized log entries
See `resources.ts` for full documentation.
### Logging
Configurable log levels: debug, info, notice, warning, error, critical, alert, emergency
## HTTP Endpoints
| Endpoint | Method | Purpose | Response |
|----------|--------|---------|----------|
| `/health` | GET | Health check | JSON status |
| `/mcp` | POST | MCP protocol | JSON response |
| `/*` | OPTIONS | CORS preflight | CORS headers |
| `/*` | GET | Server info | JSON metadata |
## Documentation Highlights
### JSDoc Annotations Used
- `@module` - Module identification
- `@class` - Class definitions
- `@constructor` - Constructor docs
- `@param` - Parameter descriptions
- `@returns` - Return values
- `@throws` - Error conditions
- `@async` - Async markers
- `@private` - Private methods
- `@see` - External links
- `@example` - Code examples
### Inline Documentation
- Section separators (`// ==================`)
- Purpose statements for each handler
- Parameter validation explanations
- Error handling rationale
- TODO notes for enhancements
## Usage Patterns
### Local Testing (Node.js)
```bash
node --loader ts-node/esm src/index.ts
```
### Development (Wrangler)
```bash
npm run dev
```
### Deployment (Cloudflare)
```bash
npm run deploy
```
### Health Check
```bash
curl http://localhost:8787/health
```
### MCP Request
```bash
curl -X POST http://localhost:8787/mcp \
-H "Content-Type: application/json" \
-d '{"method": "tools/list"}'
```
## Adding New Tools
1. **Define tool schema** in `setupHandlers()` → `ListToolsRequestSchema`:
```typescript
{
name: 'tool_name',
description: 'What it does',
inputSchema: { /* JSON Schema */ }
}
```
2. **Implement tool logic** in `setupHandlers()` → `CallToolRequestSchema`:
```typescript
case 'tool_name':
// Validate args
// Execute logic
return { content: [{ type: 'text', text: result }] };
```
## Adding New Prompts
Add to `src/prompts.ts` (see PROMPTS.md for details):
1. Define in `PROMPTS` array
2. Implement in `generatePrompt()` function
## Error Handling
All tools validate inputs and throw descriptive errors:
```typescript
if (!args || typeof args.param !== 'expected_type') {
throw new Error('Clear error message');
}
```
## Type Safety
- Full TypeScript types throughout
- MCP SDK types imported and used
- Request/Response types from Cloudflare Workers
## Environment Support
| Feature | Node.js (stdio) | Cloudflare Workers (HTTP) |
|---------|----------------|---------------------------|
| MCP Protocol | ✅ Full support | ⚠️ Basic (TODO) |
| Tools | ✅ All tools | ✅ All tools (via HTTP) |
| Prompts | ✅ All prompts | ✅ All prompts (via HTTP) |
| Health Check | ❌ N/A | ✅ /health endpoint |
## Related Documentation
- **README.md** - User guide and setup instructions
- **DOCUMENTATION.md** - Comprehensive documentation overview
- **PROMPTS.md** - Prompt system guide (if exists)
- **prompts.ts** - Prompt definitions and logic
## Common Tasks
### Check compilation
```bash
npm run types
```
### View logs (deployed)
```bash
npx wrangler tail
```
### Test health endpoint
```bash
curl http://localhost:8787/health
```
### Test tool execution
Via MCP client or HTTP POST to `/mcp` endpoint
---
**Version**: 1.0.0
**Last Updated**: October 10, 2025
**Lines of Code**: 458
**Documentation Coverage**: 100%