Skip to content

Commit eaa6df4

Browse files
committed
Enhanced error handling + new patterns to make it more type safe.
1 parent 8d4f1cf commit eaa6df4

25 files changed

+2971
-9426
lines changed

.gitignore

Lines changed: 26 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -1,99 +1,55 @@
1+
# =================================================================
2+
# .gitignore for MCP STDIO Server
3+
# =================================================================
4+
15
# Dependencies
26
node_modules/
37
npm-debug.log*
48
yarn-debug.log*
59
yarn-error.log*
610
pnpm-debug.log*
711

8-
# Runtime data
9-
pids
10-
*.pid
11-
*.seed
12-
*.pid.lock
13-
14-
# Coverage directory used by tools like istanbul
15-
coverage/
16-
*.lcov
17-
18-
# nyc test coverage
19-
.nyc_output
20-
21-
# Instrumented libs generated by jscoverage/JSCover
22-
lib-cov
23-
24-
# Compiled TypeScript
12+
# Build output
2513
dist/
2614
build/
2715
*.tsbuildinfo
16+
.tsbuildinfo
17+
18+
# Environment variables
19+
.env
20+
.env.*
21+
!.env.example
2822

2923
# Logs
30-
logs
24+
logs/
3125
*.log
3226

3327
# Runtime data
34-
pids
28+
pids/
3529
*.pid
3630
*.seed
3731
*.pid.lock
3832

39-
# Dependency directories
40-
node_modules/
41-
jspm_packages/
33+
# Coverage reports
34+
coverage/
35+
*.lcov
36+
.nyc_output
4237

43-
# Optional npm cache directory
38+
# Cache directories
4439
.npm
45-
46-
# Optional eslint cache
47-
.eslintcache
48-
49-
# Optional REPL history
50-
.node_repl_history
51-
52-
# Output of 'npm pack'
53-
*.tgz
54-
55-
# Yarn Integrity file
56-
.yarn-integrity
57-
58-
# dotenv environment variables file
59-
.env
60-
.env.test
61-
.env.production
62-
63-
# parcel-bundler cache (https://parceljs.org/)
40+
.yarn
41+
.pnpm
6442
.cache
6543
.parcel-cache
44+
.eslintcache
6645

67-
# next.js build output
68-
.next
69-
70-
# nuxt.js build output
71-
.nuxt
72-
73-
# vuepress build output
74-
.vuepress/dist
75-
76-
# Serverless directories
77-
.serverless
78-
79-
# FuseBox cache
80-
.fusebox/
81-
82-
# DynamoDB Local files
83-
.dynamodb/
84-
85-
# TernJS port file
86-
.tern-port
87-
88-
# Stores VSCode versions used for testing VSCode extensions
89-
.vscode-test
90-
91-
# IDE files
46+
# IDE and editor files
9247
.vscode/
9348
.idea/
9449
*.swp
9550
*.swo
9651
*~
52+
.vscode-test
9753

9854
# OS generated files
9955
.DS_Store
@@ -107,25 +63,14 @@ Thumbs.db
10763
# Testing
10864
test-results/
10965
playwright-report/
110-
test-results/
111-
coverage/
112-
113-
# Local development
114-
.env.local
115-
.env.development.local
116-
.env.test.local
117-
.env.production.local
11866

11967
# Temporary files
12068
*.tmp
12169
*.temp
12270

123-
# Lock files (if using different package managers)
124-
# Uncomment the appropriate one:
125-
# package-lock.json
71+
# Package manager lock files (keeping npm lock file)
12672
# yarn.lock
12773
# pnpm-lock.yaml
12874

129-
# Production builds
130-
dist/
131-
build/
75+
# Docker
76+
.dockerignore

.nvmrc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
20

CLAUDE.md

Lines changed: 160 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -4,27 +4,28 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
44

55
## Project Overview
66

7-
This repository implements a **learning-edition MCP calculator server using STDIO transport**. It demonstrates the Model Context Protocol (MCP) with standard JSON-RPC communication over stdin/stdout using the official MCP SDK.
7+
This repository is a **comprehensive educational curriculum for MCP development** built around a world-class calculator server using STDIO transport. It serves as the definitive learning resource for the MCP community, combining a production-ready server implementation with structured learning materials, progressive exercises, and complete best practices guidance.
88

99
## Development Commands
1010

1111
### Core Development
1212
- `npm install` - Install dependencies
1313
- `npm start` - Run the MCP server (`dist/server.js --stdio`)
1414
- `npm run dev` - Development mode with auto-reload
15-
- `npm run build` - Build TypeScript to JavaScript (may fail due to legacy API usage)
15+
- `npm run build` - Build TypeScript to JavaScript
16+
- `npm run format` - Format code with Prettier
17+
- `npm run format:check` - Check code formatting
1618
- `npm run clean` - Remove dist directory
1719

1820
### Testing & Quality
19-
- `npm test` - Run all tests
20-
- `npm run test:watch` - Run tests in watch mode
21-
- `npm run test:coverage` - Run tests with coverage
2221
- `npm run lint` - Run ESLint
2322
- `npm run lint:fix` - Fix linting issues
2423
- `npm run typecheck` - TypeScript type checking
24+
- `npm run format` - Format code with Prettier
25+
- `npm run format:check` - Check code formatting
2526

2627
### MCP Inspection
27-
- `npx @modelcontextprotocol/inspector --cli "node dist/server.js --stdio" --method tools/list` - List all 7 tools with schemas
28+
- `npx @modelcontextprotocol/inspector --cli "node dist/server.js --stdio" --method tools/list` - List all 8 tools with schemas
2829
- `npx @modelcontextprotocol/inspector --cli "node dist/server.js --stdio" --method prompts/list` - List all 3 prompts
2930
- `npx @modelcontextprotocol/inspector --cli "node dist/server.js --stdio" --method resources/list` - List all 4 resources
3031
- `npx @modelcontextprotocol/inspector --cli "node dist/server.js --stdio" --method resources/read --uri "calculator://constants"` - Read specific resource
@@ -41,10 +42,11 @@ The project provides a **single, production-ready MCP server implementation**:
4142
- Implements standard MCP protocol with `tools/list`, `tools/call`, `resources/list`, `prompts/list` methods
4243
- Compatible with all MCP clients and registries including Smithery
4344

44-
### MCP Golden Standard Features
45-
- **7 Tools**: `calculate`, `batch_calculate`, `advanced_calculate`, `demo_progress`, `solve_math_problem`, `explain_formula`, `calculator_assistant`
46-
- **3 Prompts**: `explain-calculation`, `generate-problems`, `calculator-tutor`
47-
- **4 Resources**: `calculator://constants`, `calculator://stats`, `formulas://library`, `calculator://history/{id}`
45+
### MCP Advanced Features Implementation
46+
- **8 Tools**: `calculate`, `batch_calculate`, `advanced_calculate`, `demo_progress`, `solve_math_problem`, `explain_formula`, `calculator_assistant`, `maintenance_mode`
47+
- **3 Prompts**: `explain-calculation`, `generate-problems`, `calculator-tutor` (all with completable arguments)
48+
- **4 Resources**: `calculator://constants`, `calculator://stats`, `formulas://library`, `calculator://history/{id}` (with completion support)
49+
- **Advanced SDK Features**: Progress notifications, interactive elicitation, dynamic lifecycle management, completable arguments
4850

4951
### State Management Architecture
5052
- **Process Memory**: All state (calculation history, request counters, uptime) stored in-memory
@@ -54,17 +56,45 @@ The project provides a **single, production-ready MCP server implementation**:
5456

5557
### Protocol Architecture
5658
- **STDIO Transport**: Pure stdin/stdout communication with newline-delimited JSON-RPC
57-
- **Progress Notifications**: Long-running operations emit progress updates via JSON-RPC notifications
59+
- **Progress Notifications**: Real-time progress updates using `sendNotification` with `notifications/progress` method
60+
- **Interactive Elicitation**: Dynamic user input collection via `server.server.elicitInput()` for ambiguous requests
61+
- **Dynamic Lifecycle**: Runtime tool enable/disable with automatic `tools/list_changed` notifications
62+
- **Completable Arguments**: Autocompletion support for prompt arguments using `completable()` wrapper
5863
- **Exit Codes**: Standard Unix exit codes (0=success, 65=data error, 70=software error)
59-
- **Concurrent Processing**: Maintains `Map<id, PromiseResolver>` for in-flight requests
60-
61-
## Development Notes
62-
63-
**Important**: The production server is the pre-built JavaScript file at `dist/server.js`. This ensures compatibility with the MCP SDK and Smithery registry. When making changes:
64-
65-
1. The working server is at `dist/server.js` (production-ready)
66-
2. TypeScript source files in `src/` are reference implementations
67-
3. Use `npm start` or `node dist/server.js --stdio` to run the server
64+
- **Error Handling**: Protocol-compliant `McpError` usage throughout
65+
66+
## Educational Curriculum Overview
67+
68+
**Important**: This is a complete educational curriculum designed for the MCP community, not just a code example.
69+
70+
### Learning Structure
71+
- **3-Week Structured Path**: Fundamentals → Advanced Patterns → Production Readiness
72+
- **4 Progressive Exercises**: From basic statistics to advanced interactive tools
73+
- **12 Key Takeaways**: Specific learning outcomes covering all MCP concepts
74+
- **Comprehensive Best Practices**: Deep dive into SDK patterns and common pitfalls
75+
- **Production Deployment**: Real-world deployment and monitoring guidance
76+
77+
### Build Process & Quality
78+
1. TypeScript source files in `src/` contain the full implementation
79+
2. `npm run build` compiles to `dist/server.js` (production-ready)
80+
3. Code is formatted with Prettier and validated with ESLint
81+
4. Zero warnings/errors policy maintained
82+
5. Use `npm start` or `node dist/server.js --stdio` to run the server
83+
84+
### Educational Content Structure
85+
- **Core Learning Objectives**: 5 major areas (Architecture, Security, Protocol, Performance, Type Safety)
86+
- **Advanced SDK Features**: Progress notifications, elicitation, lifecycle, completion
87+
- **Testing & Validation**: Comprehensive testing strategy with MCP Inspector
88+
- **Common Pitfalls**: 5 detailed pitfalls with solutions and explanations
89+
- **Learning Path**: Week-by-week curriculum for systematic learning
90+
- **Hands-on Exercises**: Progressive exercises building complexity
91+
92+
### SDK Patterns Demonstrated
93+
- **Progress Notifications**: Access `sendNotification` from handler's second parameter
94+
- **Interactive Elicitation**: Use `server.server.elicitInput()` for dynamic user input
95+
- **Tool Lifecycle**: Store handles from `registerTool()` for runtime management
96+
- **Completable Arguments**: Wrap schemas with `completable()` for autocompletion
97+
- **Error Handling**: Use `McpError` with proper error codes throughout
6898

6999
## Testing Strategy
70100

@@ -81,12 +111,115 @@ The test suite validates MCP server functionality:
81111
{"result":{"content":[{"type":"text","text":"5 + 3 = 8"}]},"jsonrpc":"2.0","id":1}
82112
```
83113

84-
## Key Implementation Files
114+
## Key Educational Resources
115+
116+
- **`README.md`** - Complete educational curriculum (3-week learning path, 4 exercises, 12 takeaways)
117+
- **`BEST_PRACTICES.md`** - Deep dive into SDK patterns and lessons learned from building world-class servers
118+
- **`src/server.ts`** - Production-quality reference implementation showcasing all advanced features
119+
- **`src/types.ts`** - Type definitions, schemas, and utility functions
120+
- **`test-elicitation.md`** - Test cases for interactive elicitation feature
121+
- **`dist/server.js`** - Compiled production server
122+
123+
## Progressive Exercise Curriculum
124+
125+
### Exercise 1: Statistics Tool (Type Safety & Registration)
126+
- Goal: Master tool registration and type safety
127+
- Task: Implement mean, median, mode, standard deviation
128+
- Learning: Zod schemas, edge case handling
129+
130+
### Exercise 2: Persistent History (Resource Management)
131+
- Goal: Advanced resource management
132+
- Task: File-based history persistence with reload
133+
- Learning: Async operations, resource lifecycle
134+
135+
### Exercise 3: Unit Conversion (Functionality Extension)
136+
- Goal: Extend server capabilities systematically
137+
- Task: Multi-unit conversion tool (length, weight, temperature)
138+
- Learning: Complex business logic, conversion matrices
139+
140+
### Exercise 4: Guided Calculation (Advanced Interactive Features)
141+
- Goal: Master all advanced SDK features combined
142+
- Task: Multi-step wizard with elicitation, progress, and lifecycle management
143+
- Learning: Complete integration of advanced patterns
144+
145+
## Advanced SDK Implementation Highlights
146+
147+
### Progress Notifications
148+
```typescript
149+
// Correct pattern: Access sendNotification from second parameter
150+
async (params, { sendNotification }) => {
151+
await sendNotification({
152+
method: "notifications/progress",
153+
params: { progressToken: id, progress: 50, message: "Halfway" }
154+
});
155+
}
156+
```
157+
158+
### Interactive Elicitation
159+
```typescript
160+
// Correct pattern: Use server.server for base Server instance
161+
const result = await server.server.elicitInput({
162+
message: "Need more information",
163+
requestedSchema: { /* JSON Schema */ }
164+
});
165+
```
166+
167+
### Dynamic Lifecycle Management
168+
```typescript
169+
// Correct pattern: Store handles for runtime control
170+
const toolHandle = server.registerTool(/* ... */);
171+
toolHandle.disable(); // Automatically sends tools/list_changed
172+
```
173+
174+
### Completable Arguments
175+
```typescript
176+
// Correct pattern: Wrap schemas with completable
177+
argsSchema: {
178+
topic: completable(z.string(), async (value) => suggestions)
179+
}
180+
```
181+
182+
## Educational Philosophy
183+
184+
This repository embodies the principle: **"Learn by building a world-class implementation."**
185+
186+
### What Makes This Special
187+
- **Complete Curriculum**: Not just code, but a full learning experience
188+
- **Community Resource**: Built for the entire MCP development community
189+
- **Progressive Learning**: From basics to advanced patterns with guided exercises
190+
- **Production Quality**: Real-world standards with zero technical debt
191+
- **Best Practices**: Hard-won insights from building world-class MCP servers
192+
193+
### Learning Outcomes
194+
After completing this curriculum, developers will master:
195+
1. All 8 MCP tools with advanced features
196+
2. 4 different resource types with completion support
197+
3. Interactive prompts with completable arguments
198+
4. Production deployment and monitoring
199+
5. Advanced SDK patterns (progress, elicitation, lifecycle)
200+
6. Common pitfalls and how to avoid them
201+
202+
The repository represents the gold standard for MCP education - a complete learning ecosystem that transforms beginners into experts through hands-on experience with production-quality code.
203+
204+
## 12 Key Learning Outcomes
205+
206+
After completing this curriculum, developers will master:
207+
208+
1. **Direct Zod schema usage** - No JSON Schema conversion needed
209+
2. **Type safety throughout** - Let TypeScript do the work
210+
3. **Simple state management** - Circular buffers over complex stores
211+
4. **Protocol compliance** - Always use McpError
212+
5. **Clean architecture** - Single responsibility principle
213+
6. **Resource completion** - Enhanced user experience
214+
7. **Proper logging** - stderr for logs, stdout for protocol
215+
8. **Process isolation** - Natural security boundary
216+
9. **Progress notifications** - Real-time feedback with sendNotification
217+
10. **Interactive elicitation** - Dynamic user input via server.server.elicitInput
218+
11. **Dynamic lifecycle** - Runtime tool management with handles
219+
12. **Completable arguments** - Autocompletion for better UX
220+
221+
## Repository Mission
85222

86-
- **`dist/server.js`** - MCP SDK server (production-ready)
87-
- **`smithery.yaml`** - Smithery registry configuration
88-
- **`smithery.json`** - MCP server manifest for registry
89-
- **`src/tests/`** - Test suite for server validation
90-
- **`mcp-demo-manifest.json`** - Feature matrix documentation
223+
**Built with ❤️ as an educational reference for the MCP community**
91224

92-
The server is built with the MCP SDK and uses standard protocol methods for maximum compatibility with all MCP clients and the Smithery registry.
225+
This repository exists to accelerate MCP adoption by providing a complete, world-class learning experience. It demonstrates that building sophisticated MCP servers is achievable when you trust the SDK, follow best practices, and focus on user experience over complexity.

0 commit comments

Comments
 (0)