patpil-cloudflare-mcp/knowledge-engine
If you are the rightful owner of knowledge-engine and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.
This template provides a comprehensive guide for setting up a production-ready Cloudflare MCP server with integrated token systems and dual transport support.
Wolfram Knowledge Engine - Quick Start Template
Production-ready template for building Cloudflare MCP servers with integrated token system.
Features
ā
Dual Transport Support - Both SSE (legacy) and Streamable HTTP (future standard)
ā
ChatGPT Ready - Works with ChatGPT out-of-the-box (requires /mcp endpoint)
ā
Claude Desktop Compatible - Works with Claude Desktop via /sse endpoint
ā
Token System Integration - Pay-per-use with shared D1 database
ā
WorkOS Magic Auth - Email + 6-digit code authentication
ā
Production-Ready - Complete error handling, logging, type safety
ā
15-30 Minute Setup - Copy, customize, deploy
Quick Setup
1. Clone and Rename
# Copy skeleton template
cp -r mcp-server-skeleton my-new-mcp
cd my-new-mcp
# Find and replace in all files:
# "WolframKnowledgeEngineMCP" ā "MyServerMCP"
# "knowledge-engine" ā "my-server-mcp"
2. Configure Secrets
# Copy environment template
cp .dev.vars.example .dev.vars
# Edit .dev.vars with your WorkOS credentials
# Get from: https://dashboard.workos.com/
# Create KV namespace
wrangler kv namespace create OAUTH_KV
# Update wrangler.jsonc with the KV ID from output
3. Install Dependencies
npm install
4. Customize Your Server
Edit these files:
src/server.ts- Replace example tools with your actual toolssrc/api-client.ts- Implement your API clientsrc/types.ts- Add custom types and bindingswrangler.jsonc- Update server name and class names
5. Test Locally
# Type check (MUST pass with zero errors)
npx tsc --noEmit
6. Deploy to Production
# Configure production secrets (first time only)
echo "client_id" | wrangler secret put WORKOS_CLIENT_ID
echo "api_key" | wrangler secret put WORKOS_API_KEY
# Deploy to Cloudflare
wrangler deploy
# Configure custom domain in Cloudflare Dashboard
# Workers & Pages ā Your Worker ā Settings ā Domains & Routes
# Add: your-server.wtyczki.ai
7. Test in Cloudflare Workers AI Playground
CRITICAL: All functional testing is done in Cloudflare Workers AI Playground at https://playground.ai.cloudflare.com/
1. Navigate to https://playground.ai.cloudflare.com/
2. Set model to one of the recommended options:
- @cf/meta/llama-3.3-70b-instruct-fp8-fast (recommended)
- @cf/mistralai/mistral-small-3.1-24b-instruct (alternative)
3. In MCP Servers section, add your server:
- SSE: https://your-server.wtyczki.ai/sse
- HTTP: https://your-server.wtyczki.ai/mcp
4. Complete OAuth flow (Magic Auth)
5. Test all tools
Available Endpoints
| Endpoint | Transport | Status | Testing |
|---|---|---|---|
/sse | Server-Sent Events | Legacy (will be deprecated) | Cloudflare Workers AI Playground |
/mcp | Streamable HTTP | New standard (recommended) | Cloudflare Workers AI Playground |
/authorize | OAuth | - | Auth flow start |
/callback | OAuth | - | Auth callback |
/token | OAuth | - | Token exchange |
/register | OAuth | - | Dynamic client registration |
Production URLs
- SSE Transport:
https://your-server.wtyczki.ai/sse - Streamable HTTP:
https://your-server.wtyczki.ai/mcp
Both transports work identically and are tested in Cloudflare Workers AI Playground after deployment.
Testing Approach
CRITICAL: All functional testing is done using Cloudflare Workers AI Playground after deployment.
Pre-Deployment (TypeScript Only):
npx tsc --noEmit # MUST pass with zero errors
Post-Deployment (Functional Testing):
- Navigate to https://playground.ai.cloudflare.com/
- Set model to one of the recommended options:
@cf/meta/llama-3.3-70b-instruct-fp8-fast(recommended)@cf/mistralai/mistral-small-3.1-24b-instruct(alternative)
- Test SSE transport:
https://your-server.wtyczki.ai/sse - Test Streamable HTTP:
https://your-server.wtyczki.ai/mcp - Verify both work identically
Validation Scripts
This skeleton integrates with workflow validation scripts that ensure quality and prevent common deployment failures.
Available Scripts:
validate-prp-schema.sh- Validate PRP structure (40+ checks)validate-runtime-secrets.sh- Verify secrets configured pre-deploymentsafe-command.sh- Environment-aware TypeScript/Wrangler command wrapperverify-security-integration.sh- Verify pilpat-mcp-security integrationverify-consistency.sh- Pre-flight configuration checkssmart-push.sh- Repository-aware git push
Documentation: See /Users/patpil/Documents/ai-projects/Cloudflare_mcp/scripts/README.md for complete usage guide.
Phase 1-3 Improvements: This skeleton benefits from comprehensive PRP execution improvements including runtime secret validation, function signature reference, security verification, and PRP schema validation. See:
PHASE_1_IMPLEMENTATION_COMPLETE.mdPHASE_2_IMPLEMENTATION_COMPLETE.mdPHASE_3_IMPLEMENTATION_COMPLETE.md
Pre-Deployment Validation
Before deploying, run the validation sequence:
# 1. Pre-flight consistency check
bash /path/to/scripts/verify-consistency.sh
# 2. Runtime secret validation (CRITICAL)
bash /path/to/scripts/validate-runtime-secrets.sh
# 3. Security integration verification (optional)
bash /path/to/scripts/verify-security-integration.sh
# 4. TypeScript compilation (using safe wrapper)
bash /path/to/scripts/safe-command.sh tsc --noEmit
Critical: Never deploy without validating secrets. TypeScript passing ā secrets configured.
Token System
How It Works
- User authenticates via WorkOS Magic Auth
- OAuth callback checks token database
- If user not in database ā 403 error page
- If user in database ā Access granted
- Each tool execution checks balance
- Tokens deducted after successful execution
- All transactions logged atomically
Example Tools Included
- simpleLookup (1 token) - Simple data lookup demonstrating low-cost operations
- searchAndAnalyze (2 tokens) - Consolidated search with filtering and analysis
- processWithSecurity (3 tokens) - Secure data processing with PII redaction and output sanitization
Phase 2 Security
Built-in security layer using pilpat-mcp-security v1.1.0+ with comprehensive PII protection.
Security Features
ā Output Sanitization
- HTML tag removal and normalization
- Control character filtering
- Whitespace cleanup
- Length limits to prevent token overflow
ā PII Redaction (US/International)
- Credit card numbers
- Social Security Numbers (SSN)
- Bank account numbers
- Email addresses (configurable - default: preserve)
- Phone numbers
ā Polish Market PII Support (Phase 2)
- PESEL (Polish national ID - 11 digits)
- Polish ID cards (3 letters + 6 digits)
- Polish passports (2 letters + 7 digits)
- Polish phone numbers (+48 prefix)
- NIP (Tax identification number)
- REGON (Business registration number)
ā Output Validation
- Type safety checks
- Size constraints
- Content integrity verification
Implementation (Step 4.5 Pattern)
Every tool follows the 7-step token pattern with Step 4.5 Security Processing:
// 4. Execute tool logic
let result = await yourToolLogic();
// 4.5. SECURITY (Phase 2)
let processed = sanitizeOutput(result, {
removeHtml: true,
removeControlChars: true,
normalizeWhitespace: true,
maxLength: 5000
});
const { redacted, detectedPII } = redactPII(processed, {
// US/International
redactPhones: true,
redactCreditCards: true,
redactSSN: true,
// Polish Market
redactPESEL: true,
redactPolishIdCard: true,
redactPolishPassport: true,
redactPolishPhones: true,
placeholder: '[REDACTED]'
});
if (detectedPII.length > 0) {
console.warn(`[Security] Redacted PII types:`, detectedPII);
}
// 5. Consume tokens (use sanitized output)
await consumeTokensWithRetry(..., redacted, ...);
// 6. Return (use sanitized output)
return { content: [{ type: "text", text: redacted }] };
Security Testing
Post-deployment security validation:
# Test HTML sanitization
curl -X POST https://your-server.wtyczki.ai/mcp \
-H "Authorization: Bearer wtyk_XXX" \
-d '{"data": "<script>alert(1)</script>Test"}'
# Test PII redaction (credit card)
curl -X POST https://your-server.wtyczki.ai/mcp \
-H "Authorization: Bearer wtyk_XXX" \
-d '{"data": "Card: 4532-1111-2222-3333"}'
# Test Polish PESEL redaction
curl -X POST https://your-server.wtyczki.ai/mcp \
-H "Authorization: Bearer wtyk_XXX" \
-d '{"data": "PESEL: 44051401359"}'
See processWithSecurity tool in src/server.ts for complete reference implementation.
Documentation
- - Step-by-step customization
- - Development guide
- - Production deployment
Note: Tool pricing is defined in each project's idea file (Section 5: Tool Pricing & Token Costs).
Project Structure
mcp-server-skeleton/
āāā src/
ā āāā index.ts # Entry point (dual transport)
ā āāā server.ts # McpAgent with example tools
ā āāā authkit-handler.ts # WorkOS OAuth + DB check
ā āāā types.ts # Type definitions
ā āāā props.ts # Auth context
ā āāā tokenUtils.ts # Token management
ā āāā api-client.ts # API client template
āāā docs/ # Detailed guides
āāā wrangler.jsonc # Cloudflare config
āāā package.json # Dependencies
āāā README.md # This file
Key TODO Items
When customizing, search for // TODO: comments in:
-
wrangler.jsonc
- Update server name
- Update class names
- Add KV namespace ID
- Add custom bindings
-
src/server.ts
- Rename
WolframKnowledgeEngineMCPclass - Replace example tools
- Update tool costs
- Update server name in
deductTokens()
- Rename
-
src/api-client.ts
- Implement actual API client
- Add API methods
- Handle authentication
-
src/types.ts
- Add custom environment variables
- Define API response types
- Add tool result types
Database Configuration
Shared D1 Database:
- ID:
ebb389aa-2d65-4d38-a0da-50c7da9dfe8b - Name:
mcp-tokens-database - DO NOT CHANGE - Must be the same across all MCP servers
Support
For issues or questions:
- Check for detailed guides
- Review example tools in
src/server.ts - Test with MCP Inspector for debugging
Next Steps
- Customize - Follow
- Test - Use both
/sseand/mcpendpoints - Deploy - Push to Cloudflare and configure domain
- Monitor - Use
wrangler tailfor live logs