Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:16:51 +08:00
commit 4e8a12140c
88 changed files with 17078 additions and 0 deletions

View File

@@ -0,0 +1,75 @@
# MCP Capability Deep-Dives
## Tools: AI-Callable Functions
**When to use**: AI needs to perform actions or fetch computed data
### Structure
- **Name**: Descriptive verb (e.g., "search_docs", "create_ticket")
- **Description**: Clear explanation (AI uses this to decide when to call)
- **Schema**: Input parameters with types and descriptions
- **Handler**: Async function returning structured content
### Example Tool Types
- Data fetching: "get_user_data", "search_products"
- Computation: "calculate_metrics", "analyze_sentiment"
- Actions: "send_email", "create_issue", "update_status"
- External APIs: "search_web", "translate_text"
---
## Resources: Data Exposure
**When to use**: AI needs to read data without side effects
### Structure
- **URI**: Pattern like "scheme://path/{param}"
- **MIME type**: Helps AI understand content format
- **Handler**: Returns content (text, JSON, binary)
### Example Resource Types
- File contents: "file:///path/to/file.txt"
- Database records: "db://users/{user_id}"
- API responses: "api://endpoint/{id}"
- Search results: "search://query/{term}"
---
## Prompts: Specialized Workflows
**When to use**: Provide templates for common tasks
### Structure
- **Name**: Descriptive identifier
- **Description**: When to use this prompt
- **Arguments**: Parameters to customize
- **Template**: Pre-filled prompt text
### Example Prompt Types
- Code review: Pre-filled checklist
- Bug triage: Structured investigation steps
- Documentation: Template with sections
---
## Common Server Patterns
### Database Integration Server
**Tools**: query_database, get_schema, list_tables
**Resources**: db://tables/{table}/schema
**Example**: PostgreSQL, MySQL, MongoDB access
### API Wrapper Server
**Tools**: call_endpoint, search_api, get_resource
**Resources**: api://endpoints/{endpoint}
**Example**: Wrap REST APIs for AI consumption
### File System Server
**Resources**: file:///{path}
**Tools**: search_files, read_file, list_directory
**Example**: Secure file access with permissions
### Workflow Automation Server
**Tools**: trigger_workflow, check_status, get_results
**Prompts**: workflow_templates
**Example**: CI/CD, deployment, data pipelines

View File

@@ -0,0 +1,91 @@
# Python MCP Server Best Practices (FastMCP)
## Setup
```bash
uv init mcp-server-name
uv add "mcp[cli]"
```
## Implementation
- ✓ Use type hints (FastMCP reads them!)
- ✓ Write detailed docstrings (becomes tool descriptions)
- ✓ Use async functions for I/O
- ✓ Handle exceptions gracefully
- ✓ Log to stderr only in STDIO mode
## Tool Definition
```python
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("server-name")
@mcp.tool()
async def search_database(query: str, limit: int = 10) -> str:
"""
Search the database for records matching the query.
Args:
query: Search terms to match against records
limit: Maximum number of results to return (default: 10)
Returns:
JSON string of matching records
"""
results = await db.search(query, limit=limit)
return json.dumps(results)
```
## Resource Definition
```python
@mcp.resource("db://tables/{table_name}/schema")
async def get_table_schema(table_name: str) -> str:
"""Get the schema for a database table."""
schema = await db.get_schema(table_name)
return json.dumps(schema)
```
## Critical Rules
### STDIO Transport
```python
import sys
# WRONG - corrupts JSON-RPC
print("Debug info")
# CORRECT - safe for STDIO
print("Debug info", file=sys.stderr)
# Or use logging
import logging
logging.basicConfig(level=logging.INFO, stream=sys.stderr)
```
### Error Handling
```python
@mcp.tool()
async def risky_operation(param: str) -> str:
"""Perform an operation that might fail."""
try:
result = await external_api.call(param)
return str(result)
except Exception as e:
logging.error(f"Operation failed: {e}")
raise ValueError(f"Operation failed: {e}")
```
## Run
```bash
# With uv
uv run main.py
# Direct
python main.py
```

View File

@@ -0,0 +1,71 @@
# TypeScript MCP Server Best Practices
## Configuration
- ✓ Use strict mode in tsconfig.json
- ✓ Target ES2022 or later
- ✓ Use Node16 module resolution
## Implementation
- ✓ Leverage Zod for runtime validation
- ✓ Export types for reusability
- ✓ Use async/await consistently
- ✓ Handle errors with try/catch
- ✓ Build before testing!
## Critical Rules
### STDIO Transport
```typescript
// WRONG - corrupts JSON-RPC
console.log("Debug info");
// CORRECT - safe for STDIO
console.error("Debug info");
```
### Tool Schemas
```typescript
import { z } from "zod";
const ToolInputSchema = z.object({
query: z.string().describe("Search query"),
limit: z.number().optional().default(10).describe("Max results"),
});
// Validate in handler
const input = ToolInputSchema.parse(request.params.arguments);
```
### Error Handling
```typescript
server.setRequestHandler(CallToolRequestSchema, async (request) => {
try {
const result = await performOperation(request.params);
return { content: [{ type: "text", text: JSON.stringify(result) }] };
} catch (error) {
console.error("Tool error:", error);
return {
content: [{
type: "text",
text: `Error: ${error.message}`
}],
isError: true
};
}
});
```
## Build & Run
```bash
# Development
npm run watch
# Production
npm run build
node build/index.js
```

View File

@@ -0,0 +1,103 @@
# MCP Server Troubleshooting
## Error Handling Patterns
### Validation Errors
```typescript
if (!isValid(input)) {
throw new Error("Invalid input: expected format X, got Y");
}
```
### API Errors
```typescript
try {
const result = await externalAPI.call();
return result;
} catch (error) {
console.error("API error:", error);
return {
content: [{
type: "text",
text: `Error: ${error.message}. Please try again.`
}]
};
}
```
### Resource Not Found
```typescript
if (!resource) {
throw new Error(`Resource not found: ${uri}`);
}
```
---
## Common Issues
| Issue | Cause | Solution |
|-------|-------|----------|
| Server not detected | Invalid path | Use absolute path, verify file exists |
| Tools don't appear | Build not run | Run `npm run build` |
| "Server error" | stdout logging | Remove console.log, use console.error |
| Connection timeout | Server crash | Check mcp-server-NAME.log for errors |
| Invalid config | JSON syntax | Validate JSON, check quotes/commas |
---
## Quick Reference Commands
### Check Claude Desktop Logs
```bash
tail -f ~/Library/Logs/Claude/mcp.log
tail -f ~/Library/Logs/Claude/mcp-server-[name].log
```
### Validate Config JSON
```bash
python -m json.tool ~/Library/Application\ Support/Claude/claude_desktop_config.json
```
### Test with MCP Inspector
```bash
npx @modelcontextprotocol/inspector [command] [args]
```
### Restart Claude Desktop
```bash
# macOS
osascript -e 'quit app "Claude"'
open -a Claude
```
---
## Transport-Specific Issues
### STDIO Transport
**Problem**: Server crashes with no error
**Cause**: Using console.log() which corrupts JSON-RPC
**Solution**: Use console.error() only
**Problem**: Server not responding
**Cause**: Blocking synchronous operation
**Solution**: Use async/await for all I/O
### HTTP Transport
**Problem**: Connection refused
**Cause**: Wrong port or server not running
**Solution**: Check PORT env var, verify server started
**Problem**: Authentication errors
**Cause**: Missing or invalid credentials
**Solution**: Configure auth headers/tokens