### Environment Variable Setup Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Instructions for setting up environment variables for local development and production secrets using Cloudflare's Wrangler CLI. ```bash cp .dev.vars.example .dev.vars ``` ```bash wrangler secret put GITHUB_CLIENT_ID wrangler secret put GITHUB_CLIENT_SECRET wrangler secret put COOKIE_ENCRYPTION_KEY wrangler secret put DATABASE_URL wrangler secret put SENTRY_DSN ``` -------------------------------- ### Simple Math MCP Server Example Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/README.md Demonstrates running a minimal MCP server with a single `calculate` tool locally using Wrangler. This example showcases core MCP components like server setup, Zod schemas for tools, and dual transport support. ```bash wrangler dev --config wrangler-simple.jsonc ``` -------------------------------- ### Core Workflow Commands Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Details essential commands for the core development workflow, including dependency installation, local development server startup, and type checking. ```bash npm install npm install --save-dev @types/package wrangler dev npm run dev npm run type-check wrangler types npx tsc --noEmit npx vitest ``` -------------------------------- ### Project Setup and Configuration Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/templates/prp_mcp_base.md Details the initial project setup, including copying configuration files, modifying server names, and setting up development environment variables for GitHub OAuth, database connection, and encryption keys. ```yaml Task 1 - Project Setup: COPY wrangler.jsonc to wrangler-[server-name].jsonc: - MODIFY name field to "[server-name]" - ADD any new environment variables to vars section - KEEP existing OAuth and database configuration CREATE .dev.vars file (if not exists): - ADD GITHUB_CLIENT_ID=your_client_id - ADD GITHUB_CLIENT_SECRET=your_client_secret - ADD DATABASE_URL=postgresql://... - ADD COOKIE_ENCRYPTION_KEY=your_32_byte_key - ADD any domain-specific environment variables ``` -------------------------------- ### Deploy to Production with Wrangler Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/claude-code-prp-setup.md Steps to set environment secrets and deploy the application using the Wrangler CLI. ```bash # Set up secrets wrangler secret put GITHUB_CLIENT_ID wrangler secret put GITHUB_CLIENT_SECRET wrangler secret put DATABASE_URL # Deploy wrangler deploy ``` -------------------------------- ### Cloudflare Workers Configuration Example Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/templates/prp_mcp_base.md Example of a Cloudflare Workers configuration file (`wrangler.jsonc`) for deployment. ```json { "name": "mcp-server", "main": "src/index.ts", "compatibility_flags": [ "workers_dev", "http_2" ], "private": true, "vars": { "DATABASE_URL": "" }, "kv_namespaces": [ { "binding": "SESSION_STORE", "id": "" } ], "durable_objects_namespaces": [ { "binding": "STATE", "id": "" } ], "routes": [ { "pattern": "/api/*", "custom_domain": true, "script": "mcp-server" } ] } ``` -------------------------------- ### Cloudflare Workers Setup Documentation Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/plan.md This documentation covers patterns for deploying Cloudflare Workers, offering guidance on setup and best practices for MCP server integration. ```markdown `PRPs/ai_docs/cloudflare_workers_setup.md` - Workers deployment patterns ``` -------------------------------- ### Create Environment Variables File Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/README.md Copies the example environment variables file to `.dev.vars` for local development configuration. ```bash cp .dev.vars.example .dev.vars ``` -------------------------------- ### Project Structure Overview Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Illustrates the typical directory and file structure for the MCP server project. This helps in understanding the organization of source code, configuration files, and documentation. ```json ├── src/ │ ├── index.ts │ ├── index_sentry.ts │ ├── simple-math.ts │ ├── github-handler.ts │ ├── database.ts │ ├── utils.ts │ └── workers-oauth-utils.ts ├── PRPs/ │ ├── README.md │ └── templates/ │ └── prp_base.md ├── wrangler.jsonc ├── wrangler-simple.jsonc ├── package.json ├── tsconfig.json ├── worker-configuration.d.ts └── CLAUDE.md ``` -------------------------------- ### Console Logging Patterns Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Provides examples of console logging for various events in the application, including database operations, authentication events, and tool execution. It shows how to log success messages, errors, and user-specific information. ```typescript // Database operations console.log(`Database operation completed successfully in ${duration}ms`); console.error(`Database operation failed after ${duration}ms:`, error); // Authentication events console.log(`User authenticated: ${this.props.login} (${this.props.name})`); // Tool execution console.log(`Tool called: ${toolName} by ${this.props.login}`); console.error(`Tool failed: ${toolName}`, error); ``` -------------------------------- ### Create and Execute MCP Server PRP Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/claude-code-prp-setup.md Commands to initiate the creation of a new MCP server using a PRP (Project Requirement Package) and then execute that PRP. ```bash # Start Claude Code in your project claude-code # Create a PRP for your MCP server /prp-mcp-create "Build an MCP server for [your use case]" # Execute the generated PRP /prp-mcp-execute [generated-prp-file.md] ``` -------------------------------- ### Claude Code Project Structure Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/claude-code-prp-setup.md Illustrates the directory and file structure created by Claude Code for an MCP server project. ```APIDOC Project Structure: .claude/ ├── commands/ │ ├── prp-mcp-create.md # Creates MCP server PRPs │ └── prp-mcp-execute.md # Executes MCP server PRPs PRPs/ ├── templates/ │ ├── prp_base.md # General PRP template (existing) │ ├── prp_mcp_server.md # Session 1 template │ └── prp_mcp_base.md # Session 3 template (primary) └── ai_docs/ ├── mcp_patterns.md # Core development patterns ├── cloudflare_workers_setup.md # Deployment guide └── oauth_integration.md # Authentication patterns CLAUDE.md # Adapted implementation guide ``` -------------------------------- ### Essential npm Commands Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Provides a list of essential npm commands for managing project dependencies and running scripts. These commands are crucial for setting up and maintaining the Node.js project. ```bash npm install npm install package-name npm install --save-dev package-name npm uninstall package-name npm update npm run dev npm run deploy npm run type-check ``` -------------------------------- ### Environment Variables Configuration Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/README.md Example configuration for the `.dev.vars` file, including GitHub OAuth credentials, database connection URL, and optional Sentry DSN. ```bash # GitHub OAuth (for authentication) GITHUB_CLIENT_ID=your_github_client_id GITHUB_CLIENT_SECRET=your_github_client_secret COOKIE_ENCRYPTION_KEY=your_random_encryption_key # Database Connection DATABASE_URL=postgresql://username:password@localhost:5432/database_name # Optional: Sentry monitoring SENTRY_DSN=https://your-sentry-dsn@sentry.io/project-id NODE_ENV=development ``` -------------------------------- ### Wrangler CLI Commands Reference Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/claude-code-prp-setup.md Provides a comprehensive reference for Cloudflare Wrangler CLI commands used in deploying and managing Node.js/TypeScript applications. Includes commands for development, deployment, secrets management, KV storage, and monitoring. ```APIDOC Wrangler CLI Commands: Development: `wrangler dev [--config ]` Starts a local development server for testing. --config: Optional path to a wrangler.toml configuration file. Deployment: `wrangler deploy [--dry-run]` Deploys the application to Cloudflare Workers. --dry-run: Simulates deployment without making changes. Secrets Management: `wrangler secret put ` Uploads a secret to the Workers environment. `wrangler secret list` Lists all secrets in the current environment. `wrangler secret delete ` Deletes a secret from the current environment. KV Storage: `wrangler kv namespace create ` Creates a new KV namespace. `wrangler kv namespace list` Lists all available KV namespaces. Monitoring: `wrangler tail` Streams logs from deployed Workers. `wrangler types` Generates TypeScript types for KV namespaces and Durable Objects. ``` -------------------------------- ### Local Development Server Start Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/README.md Command to start the MCP server locally for development and testing. The server will be accessible at http://localhost:8792. ```bash wrangler dev ``` -------------------------------- ### Input Validation with Zod Schema Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Demonstrates how to define and use Zod schemas for validating tool inputs, ensuring data integrity and type safety. The example shows a `DatabaseQuerySchema` with specific constraints on SQL queries and an optional limit parameter. ```typescript import { z } from "zod"; // Define validation schemas const DatabaseQuerySchema = z.object({ sql: z .string() .min(1, "SQL query cannot be empty") .refine((sql) => sql.trim().toLowerCase().startsWith("select"), { message: "Only SELECT queries are allowed", }), limit: z.number().int().positive().max(1000).optional(), }); // Use in tool definition this.server.tool( "queryDatabase", "Execute a read-only SQL query", DatabaseQuerySchema, // Zod schema provides automatic validation async ({ sql, limit }) => { // sql and limit are already validated and properly typed const results = await db.unsafe(sql); return { content: [{ type: "text", text: JSON.stringify(results, null, 2) }] }; }, ); ``` -------------------------------- ### Wrangler Configuration Example Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/ai_docs/mcp_patterns.md Provides a sample `wrangler.toml` file demonstrating the basic structure for configuring a Cloudflare Worker project. It includes project name, entry point, compatibility date, and KV namespace bindings. ```toml name = "mcp-server" main = "src/index.ts" compatibility_date = "2024-01-01" [[kv_namespaces]] binding = "OAUTH_KV" id = "your-kv-namespace-id" [env.production] # Production-specific configuration ``` -------------------------------- ### Code Quality Tools Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Commands for maintaining code quality using Prettier for formatting and ESLint for linting TypeScript code. ```bash npx prettier --write . ``` ```bash npx eslint src/ ``` -------------------------------- ### Install and Run MCP Inspector Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/README.md Installs the MCP Inspector tool globally and runs it to test the MCP server. It allows connecting to the server via different transports and interacting with available tools. ```bash npx @modelcontextprotocol/inspector@latest ``` -------------------------------- ### Claude Desktop Integration Configuration Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md JSON configurations for integrating with Claude Desktop, specifying the command and arguments to connect to local development or production MCP servers. ```json { "mcpServers": { "database-mcp": { "command": "npx", "args": ["mcp-remote", "http://localhost:8788/mcp"], "env": {} } } } ``` ```json { "mcpServers": { "database-mcp": { "command": "npx", "args": ["mcp-remote", "https://your-worker.workers.dev/mcp"], "env": {} } } } ``` -------------------------------- ### MCP Server Creation Command Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/claude-code-prp-setup.md Demonstrates the command used to initiate the creation of a new MCP server Product Requirement Prompt (PRP). It outlines the process Claude Code follows, including planning, analysis, template customization, and integration of documentation. ```bash # Developer runs: /prp-mcp-create "Build an MCP server for weather data with caching" # Claude Code: 1. Uses TodoWrite to plan research 2. Analyzes existing codebase patterns 3. Reads PRPs/templates/prp_mcp_base.md 4. Customizes template with specific requirements 5. Includes all necessary context from ai_docs 6. Generates comprehensive PRP document ``` -------------------------------- ### Essential Wrangler CLI Commands Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Outlines critical Wrangler CLI commands for Cloudflare Workers development, testing, and deployment. This includes authentication, local development, and deployment procedures. ```bash wrangler login wrangler logout wrangler whoami wrangler dev wrangler deploy wrangler deploy --dry-run wrangler types ``` -------------------------------- ### Install Wrangler CLI Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/README.md Installs the Wrangler CLI globally, which is used to manage Cloudflare Workers deployments and development. ```bash npm install -g wrangler ``` -------------------------------- ### Local Development MCP Server Commands Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Bash commands to run the main MCP server with OAuth and a simple MCP server without authentication using Cloudflare's Wrangler CLI. ```bash wrangler dev # Available at http://localhost:8788/mcp ``` ```bash wrangler dev --config wrangler-simple.jsonc # Port 8789 ``` -------------------------------- ### Git Commit Workflow Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Outlines the recommended Git workflow, including pre-commit checks for type compilation and deployment configuration, and emphasizes the use of descriptive commit messages for better version control. ```bash # Before committing, always run: npm run type-check # Ensure TypeScript compiles wrangler dev --dry-run # Test deployment configuration # Commit with descriptive messages git add . git commit -m "feat: add new MCP tool for database queries" ``` -------------------------------- ### Local Development Testing (Bash) Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/templates/prp_mcp_base.md Contains bash commands to start the local development server using `wrangler dev` and test the OAuth flow and MCP endpoint via `curl`. It outlines expected outcomes and troubleshooting steps. ```bash # Start local development server wrangler dev # Test OAuth flow (should redirect to GitHub) curl -v http://localhost:8788/authorize # Test MCP endpoint (should return server info) curl -v http://localhost:8788/mcp # Expected: Server starts, OAuth redirects to GitHub, MCP responds with server info # If errors: Check console output, verify environment variables, fix configuration ``` -------------------------------- ### GitHub OAuth App Configuration Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/templates/prp_mcp_base.md Guides on creating or reusing a GitHub OAuth application, including setting the homepage and callback URLs, and verifying client ID and secret in the environment. ```yaml Task 2 - GitHub OAuth App: CREATE new GitHub OAuth app: - SET homepage URL: https://your-worker.workers.dev - SET callback URL: https://your-worker.workers.dev/callback - COPY client ID and secret to .dev.vars OR REUSE existing OAuth app: - UPDATE callback URL if using different subdomain - VERIFY client ID and secret in environment ``` -------------------------------- ### MCP Server Security Considerations Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/claude-code-prp-setup.md Outlines the security measures implemented in the MCP server to protect against common vulnerabilities. ```APIDOC Security Considerations: - SQL injection protection via pattern validation. - HMAC-signed cookies for OAuth approval. - Role-based access control for tools. - Error message sanitization. ``` -------------------------------- ### MCP Server Technical Architecture Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/claude-code-prp-setup.md Details the core technologies and architectural components used in the MCP server implementation. ```APIDOC MCP Server Architecture: - Cloudflare Workers: Serverless runtime with global distribution. - Durable Objects: Stateful MCP agent persistence. - GitHub OAuth: Secure authentication with permission management. - PostgreSQL: Database integration with connection pooling. ``` -------------------------------- ### Database Connection Management Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md TypeScript code for managing PostgreSQL database connections using a singleton pattern within Cloudflare Workers, including connection pooling and error handling. ```typescript // Singleton connection pool with Cloudflare Workers limits export function getDb(databaseUrl: string): postgres.Sql { if (!dbInstance) { dbInstance = postgres(databaseUrl, { max: 5, // Max 5 connections for Workers idle_timeout: 20, connect_timeout: 10, prepare: true, // Enable prepared statements }); } return dbInstance; } // Connection wrapper with error handling export async function withDatabase(databaseUrl: string, operation: (db: postgres.Sql) => Promise): Promise { const db = getDb(databaseUrl); // Execute operation with timing and error handling } ``` -------------------------------- ### MCP Server PRP Execution Command Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/claude-code-prp-setup.md Illustrates the command for executing a previously generated MCP server PRP. This process involves validation and a multi-stage deployment, ensuring the server is built according to the specified requirements. ```bash # Developer runs: /prp-mcp-execute weather-mcp-server.md ``` -------------------------------- ### Production Monitoring Deployment Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Outlines the process for deploying the application with Sentry monitoring enabled in a production environment. This includes setting production secrets for Sentry DSN and Node.js environment, and deploying using Wrangler. ```bash # Set production secrets wrangler secret put SENTRY_DSN wrangler secret put NODE_ENV # Set to "production" # Deploy with monitoring wrangler deploy ``` -------------------------------- ### Development Monitoring Configuration with Sentry Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Details the steps to configure Sentry integration for local development using environment variables. It involves setting the Sentry DSN and Node.js environment, and running the development server with the Sentry-enabled entry point. ```bash # Enable Sentry in development echo 'SENTRY_DSN=https://your-dsn@sentry.io/project' >> .dev.vars echo 'NODE_ENV=development' >> .dev.vars # Use Sentry-enabled version wrangler dev --config wrangler.jsonc # Ensure main = "src/index_sentry.ts" ``` -------------------------------- ### Authenticated Database MCP Server Implementation Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md TypeScript code defining an authenticated MCP server using the MCP SDK and McpServer for a PostgreSQL database. It outlines available MCP tools and their access levels. ```typescript export class MyMCP extends McpAgent, Props> { server = new McpServer({ name: "PostgreSQL Database MCP Server", version: "1.0.0", }); // MCP Tools available based on user permissions // - listTables (all users) // - queryDatabase (all users, read-only) // - executeDatabase (privileged users only) } ``` -------------------------------- ### Database Connection String Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/README.md Provides examples of PostgreSQL connection strings for both local and hosted services like Supabase. This string is used to configure the DATABASE_URL environment variable. ```plaintext DATABASE_URL=postgresql://username:password@host:5432/database_name ``` ```plaintext Local: postgresql://myuser:mypass@localhost:5432/mydb ``` ```plaintext Supabase: postgresql://postgres:your-password@db.your-project.supabase.co:5432/postgres ``` -------------------------------- ### MCP Database Tool Implementations Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Details the implementation pattern for MCP tools interacting with a PostgreSQL database. It showcases the `queryDatabase` tool, which performs read-only SQL queries, including input validation against SQL injection and write operations. ```typescript this.server.tool( "queryDatabase", "Execute a read-only SQL query against the PostgreSQL database.", { sql: z.string().describe("SQL query - SELECT statements only"), }, async ({ sql }) => { try { const validation = validateSqlQuery(sql); if (!validation.isValid) { return { content: [{ type: "text", text: `Invalid SQL: ${validation.error}`, isError: true }] }; } if (isWriteOperation(sql)) { return { content: [{ type: "text", text: "Write operations not allowed", isError: true }] }; } return await withDatabase(this.env.DATABASE_URL, async (db) => { const results = await db.unsafe(sql); return { content: [ { type: "text", text: `**Results:** ```json ${JSON.stringify(results, null, 2)} ````, }, ], }; }); } catch (error) { return { content: [{ type: "text", text: `Error: ${formatDatabaseError(error)}`, isError: true }] }; } }, ); ``` -------------------------------- ### Sentry Integration for Cloudflare Workers Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Demonstrates how to integrate Sentry SDK into a Cloudflare Worker for error tracking, performance monitoring, and distributed tracing. It includes setting up Sentry configuration, instrumenting tool calls with traces and spans, and binding user context. ```typescript import * as Sentry from "@sentry/cloudflare"; // Sentry configuration function getSentryConfig(env: Env) { return { dsn: env.SENTRY_DSN, tracesSampleRate: 1, // 100% trace sampling }; } // Instrument MCP tools with tracing private registerTool(name: string, description: string, schema: any, handler: any) { this.server.tool(name, description, schema, async (args: any) => { return await Sentry.startNewTrace(async () => { return await Sentry.startSpan({ name: `mcp.tool/${name}`, attributes: extractMcpParameters(args), }, async (span) => { // Set user context Sentry.setUser({ username: this.props.login, email: this.props.email, }); try { return await handler(args); } catch (error) { span.setStatus({ code: 2 }); // error return handleError(error); // Returns user-friendly error with event ID } }); }); }); } ``` -------------------------------- ### Authenticated User Context and Permissions Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Defines the structure for authenticated user properties (`Props`) including GitHub username, display name, email, and access token. It also shows how to access this user context within MCP tools to determine permissions, such as write access. ```typescript type Props = { login: string; // GitHub username name: string; // Display name email: string; // Email address accessToken: string; // GitHub access token }; // Available in MCP tools via this.props class MyMCP extends McpAgent, Props> { async init() { // Access user context in any tool const username = this.props.login; const hasWriteAccess = ALLOWED_USERNAMES.has(username); } } ``` -------------------------------- ### Standardized MCP Tool with Zod Validation Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Showcases a TypeScript tool implementation that adheres to the project's standards, including Zod for input validation and a standardized response format for both success and error scenarios. This ensures consistency and robustness in tool interactions. ```typescript import { z } from "zod"; // Tool with proper TypeScript patterns this.server.tool( "standardizedTool", "Tool following standard response format", { name: z.string().min(1, "Name cannot be empty"), options: z.object({}).optional(), }, async ({ name, options }) => { try { // Input already validated by Zod schema const result = await processName(name, options); // Return standardized success response return { content: [ { type: "text", text: `**Success**\n\nProcessed: ${name}\n\n**Result:**\n```json ${JSON.stringify(result, null, 2)} ```\n\n**Processing time:** 0.5s`, }, ], }; } catch (error) { // Return standardized error response return { content: [ { type: "text", text: `**Error**\n\nProcessing failed: ${error instanceof Error ? error.message : String(error)}`, isError: true, }, ], }; } }, ); ``` -------------------------------- ### Structured Error Handling for Database Operations Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Illustrates a function for sanitizing and formatting database errors to provide user-friendly messages while preventing sensitive information leakage. It handles specific error conditions like authentication failures and timeouts. ```typescript // Error sanitization for security export function formatDatabaseError(error: unknown): string { if (error instanceof Error) { if (error.message.includes("password")) { return "Database authentication failed. Please check credentials."; } if (error.message.includes("timeout")) { return "Database connection timed out. Please try again."; } return `Database error: ${error.message}`; } return "Unknown database error occurred."; } ``` -------------------------------- ### Database Connection and Operation Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/ai_docs/mcp_patterns.md Provides a pattern for interacting with a database using a helper function `withDatabase` that manages connections. It includes SQL query validation using `validateSqlQuery` and error formatting with `formatDatabaseError`. The example demonstrates executing a query and returning results, handling potential validation or execution errors. ```typescript import { withDatabase, validateSqlQuery, isWriteOperation, formatDatabaseError } from "./database"; // Database operation with connection management async function performDatabaseOperation(sql: string) { try { // Validate SQL query const validation = validateSqlQuery(sql); if (!validation.isValid) { return { content: [ { type: "text", text: `Invalid SQL query: ${validation.error}`, isError: true } ] }; } // Execute with automatic connection management return await withDatabase(this.env.DATABASE_URL, async (db) => { const results = await db.unsafe(sql); return { content: [ { type: "text", text: `**Query Results**\n```sql\n${sql}\n```\n\n**Results:**\n```json\n${JSON.stringify(results, null, 2)} ```\n\n**Rows returned:** ${Array.isArray(results) ? results.length : 1}` } ] }; }); } catch (error) { console.error('Database operation error:', error); return { content: [ { type: "text", text: `Database error: ${formatDatabaseError(error)}`, isError: true } ] }; } } ``` -------------------------------- ### MCP Development Patterns Documentation Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/plan.md This file serves as a documentation resource for core MCP development patterns, providing rich context for PRP generation and AI agent referencing. ```markdown `PRPs/ai_docs/mcp_patterns.md` - Core MCP development patterns ``` -------------------------------- ### Production Deployment Commands Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/templates/prp_mcp_base.md Commands for deploying the application to Cloudflare Workers and verifying the deployment. ```bash Task 7 - Production Deployment: DEPLOY to Cloudflare Workers: - RUN: wrangler deploy - VERIFY deployment success - TEST production OAuth flow - VERIFY MCP endpoint accessibility ``` -------------------------------- ### Database Integration (YAML) Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/templates/prp_mcp_base.md Provides guidance on database integration, recommending PostgreSQL connection pooling, using the `DATABASE_URL` environment variable, and emphasizing security practices like `validateSqlQuery` and `isWriteOperation`. ```yaml DATABASE: - PostgreSQL connection: Use existing connection pooling patterns - Environment variable: DATABASE_URL with full connection string - Security: Use validateSqlQuery and isWriteOperation for all SQL ``` -------------------------------- ### Database Integration Testing (Bash) Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/templates/prp_mcp_base.md Illustrates bash commands for testing database integration by calling MCP methods to list tables and testing permission validation and SQL injection protection. ```bash # Test database connection curl -X POST http://localhost:8788/mcp \ -H "Content-Type: application/json" \ -d '{"method": "tools/call", "params": {"name": "listTables", "arguments": {}}}' # Test permission validation # Test SQL injection protection ``` -------------------------------- ### Running Tests Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/README.md Commands to execute the project's test suite, including options for running UI tests. ```bash npm test npm run test:ui ``` -------------------------------- ### MCP Server Implementation Pattern (TypeScript) Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/templates/prp_mcp_base.md Demonstrates the core structure of an MCP agent server, including initialization, cleanup, and tool registration. It highlights patterns for basic and privileged tools, emphasizing error handling and permission checks. ```typescript export class YourMCP extends McpAgent, Props> { server = new McpServer({ name: "Your MCP Server Name", version: "1.0.0", }); async cleanup(): Promise { try { await closeDb(); console.log("Database connections closed successfully"); } catch (error) { console.error("Error during database cleanup:", error); } } async alarm(): Promise { await this.cleanup(); } async init() { this.registerBasicTools(); this.registerPrivilegedTools(); } private registerBasicTools() { this.server.tool( "yourBasicTool", "Description of your basic tool", YourToolSchema, // Zod validation schema async ({ param1, param2, options }) => { try { const result = await performOperation(param1, param2, options); return { content: [ { type: "text", text: `**Success**\n\nOperation completed\n\n**Result:**\n```json ${JSON.stringify(result, null, 2)} ````, }, ], }; } catch (error) { return createErrorResponse(`Operation failed: ${error.message}`); } }, ); } private registerPrivilegedTools() { const PRIVILEGED_USERS = new Set(["admin1", "admin2"]); if (PRIVILEGED_USERS.has(this.props.login)) { this.server.tool("privilegedTool", "Administrative tool for privileged users", { action: z.string() }, async ({ action }) => { if (!PRIVILEGED_USERS.has(this.props.login)) { return createErrorResponse("Insufficient permissions"); } return { content: [ { type: "text", text: `Admin action '${action}' executed by ${this.props.login}`, }, ], }; }); } } } ``` -------------------------------- ### HMAC-Signed Approval Cookies Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Details the implementation of HMAC-signed cookies for client approval in the OAuth flow. It includes functions for generating a signature for data using a cryptographic key and verifying the integrity of a cookie by comparing its signature. ```typescript // Generate signed cookie for client approval async function signData(key: CryptoKey, data: string): Promise { const signatureBuffer = await crypto.subtle.sign("HMAC", key, enc.encode(data)); return Array.from(new Uint8Array(signatureBuffer)) .map((b) => b.toString(16).padStart(2, "0")) .join(""); } // Verify cookie integrity async function verifySignature(key: CryptoKey, signatureHex: string, data: string): Promise { const signatureBytes = new Uint8Array(signatureHex.match(/.{1,2}/g)!.map((byte) => parseInt(byte, 16))); return await crypto.subtle.verify("HMAC", key, signatureBytes.buffer, enc.encode(data)); } ``` -------------------------------- ### Environment Configuration and Secrets Management Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/templates/prp_mcp_base.md Steps for setting up Cloudflare KV namespaces and managing production secrets, including creating namespaces and using `wrangler secret put` for sensitive variables. ```yaml Task 5 - Environment Configuration: SETUP Cloudflare KV namespace: - RUN: wrangler kv namespace create "OAUTH_KV" - UPDATE wrangler.jsonc with returned namespace ID SET production secrets: - RUN: wrangler secret put GITHUB_CLIENT_ID - RUN: wrangler secret put GITHUB_CLIENT_SECRET - RUN: wrangler secret put DATABASE_URL - RUN: wrangler secret put COOKIE_ENCRYPTION_KEY ``` -------------------------------- ### Access Control for Write Operations Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Implements access control by defining a set of allowed GitHub usernames that can execute write operations. This is demonstrated by conditionally registering the `executeDatabase` tool based on the authenticated user's login. ```typescript const ALLOWED_USERNAMES = new Set([ 'coleam00' // Only these GitHub usernames can execute write operations ]); // Tool availability based on user permissions if (ALLOWED_USERNAMES.has(this.props.login)) { // Register executeDatabase tool for privileged users this.server.tool("executeDatabase", ...); } ``` -------------------------------- ### Conditional Tool Registration (Permissions) Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/ai_docs/mcp_patterns.md Illustrates how to conditionally register tools based on user permissions. This example checks if the logged-in user's login name is in an allowed set before registering a 'privilegedTool', ensuring that sensitive operations are only available to authorized users. ```typescript // Permission-based tool availability const ALLOWED_USERNAMES = new Set([ 'admin1', 'admin2' ]); // Register privileged tools only for authorized users if (ALLOWED_USERNAMES.has(this.props.login)) { this.server.tool( "privilegedTool", "Tool only available to authorized users", { /* parameters */ }, async (params) => { // Privileged operation return { content: [ { type: "text", text: `Privileged operation executed by: ${this.props.login}` } ] }; } ); } ``` -------------------------------- ### Standardized Error Response Utility Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Provides a utility function `createErrorResponse` for generating consistent error messages within the application. It includes options for adding detailed error information in a JSON format, useful for debugging and client-side handling. ```typescript // Error handling utility function createErrorResponse(message: string, details?: any): any { return { content: [{ type: "text", text: `**Error**\n\n${message}${details ? `\n\n**Details:**\n```json\n${JSON.stringify(details, null, 2)}```` : ''}`, isError: true }] }; } // Permission error if (!ALLOWED_USERNAMES.has(this.props.login)) { return createErrorResponse( "Insufficient permissions for this operation", { requiredRole: "privileged", userRole: "standard" } ); } // Validation error if (isWriteOperation(sql)) { return createErrorResponse( "Write operations not allowed with this tool", { operation: "write", allowedOperations: ["select", "show", "describe"] } ); } // Database error catch (error) { return createErrorResponse( "Database operation failed", { error: formatDatabaseError(error) } ); } ``` -------------------------------- ### Local Testing Commands Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/templates/prp_mcp_base.md Commands for running the server locally and testing its basic functionality, including the OAuth flow and MCP endpoint. ```bash Task 6 - Local Testing: TEST basic functionality: - RUN: wrangler dev - VERIFY server starts without errors - TEST OAuth flow: http://localhost:8788/authorize - VERIFY MCP endpoint: http://localhost:8788/mcp ``` -------------------------------- ### Basic Tool Registration Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/ai_docs/mcp_patterns.md Demonstrates how to register a new tool with the MCP server. It defines the tool's name, a description for LLM understanding, input parameters using Zod for validation, and an asynchronous function to execute the tool's logic. Error handling for tool execution is included. ```typescript // Basic tool registration this.server.tool( "toolName", "Tool description for the LLM", { param1: z.string().describe("Parameter description"), param2: z.number().optional().describe("Optional parameter"), }, async ({ param1, param2 }) => { try { // Tool implementation const result = await performOperation(param1, param2); return { content: [ { type: "text", text: `Success: ${JSON.stringify(result, null, 2)}` } ] }; } catch (error) { console.error('Tool error:', error); return { content: [ { type: "text", text: `Error: ${error.message}`, isError: true } ] }; } } ); ``` -------------------------------- ### Configuring Sentry (Development) Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/README.md Instructions for enabling Sentry in a development environment by adding the SENTRY_DSN to the .dev.vars file and running the application with `wrangler dev`. ```bash SENTRY_DSN=https://your-sentry-dsn@sentry.io/project-id NODE_ENV=development wrangler dev ``` -------------------------------- ### SQL Injection Protection Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Provides functions to validate SQL queries against dangerous patterns and to determine if a query is a write operation. This helps prevent SQL injection attacks by sanitizing input and enforcing read-only access for certain operations. ```typescript export function validateSqlQuery(sql: string): { isValid: boolean; error?: string } { const dangerousPatterns = [ /;s*drops+/i, /;s*deletes+.*s+wheres+1s*=s*1/i, /;s*truncates+/i, // ... more patterns ]; // Pattern-based validation for safety return { isValid: true }; // Placeholder } export function isWriteOperation(sql: string): boolean { const writeKeywords = ["insert", "update", "delete", "create", "drop", "alter"]; return writeKeywords.some((keyword) => sql.trim().toLowerCase().startsWith(keyword)); } ``` -------------------------------- ### KV Storage Configuration (YAML) Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/templates/prp_mcp_base.md Explains the use of KV storage for OAuth state management, including namespace creation via `wrangler kv namespace create` and configuration within `wrangler.jsonc` bindings. ```yaml KV_STORAGE: - OAuth state: Used by OAuth provider for state management - Namespace: Create with `wrangler kv namespace create "OAUTH_KV"` - Configuration: Add namespace ID to wrangler.jsonc bindings ``` -------------------------------- ### Environment Variables Configuration (YAML) Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/templates/prp_mcp_base.md Lists essential environment variables for development and production, including GitHub OAuth credentials, database URL, and encryption key, and specifies the use of `.dev.vars` for local testing. ```yaml ENVIRONMENT_VARIABLES: - Development: .dev.vars file for local testing - Production: Cloudflare Workers secrets for deployment - Required: GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, DATABASE_URL, COOKIE_ENCRYPTION_KEY ``` -------------------------------- ### OAuth Integration Documentation Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/plan.md This documentation details the process of integrating OAuth for authentication flows within MCP servers, outlining common patterns and considerations. ```markdown `PRPs/ai_docs/oauth_integration.md` - Authentication flow documentation ``` -------------------------------- ### Write Operation Check Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/ai_docs/mcp_patterns.md A utility pattern to prevent unauthorized write operations within a tool. It uses the `isWriteOperation` function to check if the provided SQL query is a write command. If it is, an error message is returned, guiding the user to use appropriate privileged tools. ```typescript // Check if operation is read-only if (isWriteOperation(sql)) { return { content: [ { type: "text", text: "Write operations are not allowed with this tool. Use the privileged tool if you have write permissions.", isError: true } ] }; } ``` -------------------------------- ### MCP Server Implementation Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/templates/prp_mcp_base.md Instructions for implementing the MCP server logic, including copying class structures, modifying server details, implementing domain-specific tools, and ensuring proper error handling and permission checks. ```yaml Task 3 - MCP Server Implementation: CREATE src/[server-name].ts OR MODIFY src/index.ts: - COPY class structure from src/index.ts - MODIFY server name and version in McpServer constructor - IMPLEMENT your domain-specific tools using existing patterns - KEEP authentication and database patterns identical IMPLEMENT MCP tools: - MIRROR tool registration pattern from src/index.ts - USE Zod schemas for input validation - IMPLEMENT proper error handling with createErrorResponse - ADD permission checking for sensitive operations ``` -------------------------------- ### Basic Resource Registration Pattern Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/ai_docs/mcp_patterns.md Shows a pattern for registering resources with a server. It defines a resource URI, description, and an asynchronous handler function that fetches data based on the resource ID and returns it in a structured format. ```typescript // Resource registration this.server.resource( "resource://example/{id}", "Resource description", async (uri) => { const id = uri.path.split('/').pop(); try { const data = await fetchResourceData(id); return { contents: [ { uri: uri.href, mimeType: "application/json", text: JSON.stringify(data, null, 2) } ] }; } catch (error) { throw new Error(`Failed to fetch resource: ${error.message}`); } } ); ``` -------------------------------- ### GitHub OAuth 2.0 Authentication Flow Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/CLAUDE.md Describes the GitHub OAuth 2.0 authentication process, including the authorization request endpoint and the callback handler. It covers checking for existing approvals via signed cookies and exchanging the authorization code for an access token to fetch user information. ```typescript // 1. Authorization Request app.get("/authorize", async (c) => { const oauthReqInfo = await c.env.OAUTH_PROVIDER.parseAuthRequest(c.req.raw); // Check if client already approved via signed cookie if (await clientIdAlreadyApproved(c.req.raw, oauthReqInfo.clientId, c.env.COOKIE_ENCRYPTION_KEY)) { return redirectToGithub(c.req.raw, oauthReqInfo, c.env, {}); } // Show approval dialog return renderApprovalDialog(c.req.raw, { client, server, state }); }); // 2. GitHub Callback app.get("/callback", async (c) => { // Exchange code for access token const [accessToken, errResponse] = await fetchUpstreamAuthToken({ client_id: c.env.GITHUB_CLIENT_ID, client_secret: c.env.GITHUB_CLIENT_SECRET, code: c.req.query("code"), redirect_uri: new URL("/callback", c.req.url).href, }); // Get GitHub user info const user = await new Octokit({ auth: accessToken }).rest.users.getAuthenticated(); // Complete authorization with user props return c.env.OAUTH_PROVIDER.completeAuthorization({ props: { accessToken, email, login, name } as Props, userId: login, }); }); ``` -------------------------------- ### GitHub OAuth Integration (YAML) Source: https://github.com/coleam00/remote-mcp-server-with-auth/blob/main/PRPs/templates/prp_mcp_base.md Outlines the steps for integrating with GitHub OAuth, including creating a GitHub App, storing client credentials as Cloudflare Workers secrets, and ensuring the callback URL matches the Workers domain. ```yaml GITHUB_OAUTH: - GitHub App: Create with callback URL matching your Workers domain - Client credentials: Store as Cloudflare Workers secrets - Callback URL: Must match exactly: https://your-worker.workers.dev/callback ```