agentleFS
brendadeeznuts1111brendadeeznuts1111/betting-brain-v3/.cursor/rules/endpoint-routing.mdc

betting-brain-v3 / rules

Cursor rule8 starsChanged 14 months agoMITView on GitHub

Endpoint routing patterns and request handling conventions

  • Sends data out

The file

We split this endpoint-routing.mdc into the rules it gives an agent

4 rules. About 0 are common, 2 are distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    All HTTP requests are handled in src/index.ts via the fetch() handler.

    line 57
  2. Distinctive:

    Used By: All dashboards, monitoring tools, browser extension

    line 101
  3. Distinctive:

    Add tool definition with schema

    line 453
  4. Very specific:

    [src/shared/constants.ts](mdc:src/shared/constants.ts): - All constants ⭐ NEW

    line 587

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
endpoint-routing.mdc
---
version: "2.0.0"
globs: "src/index.ts,src/**/*.ts"
alwaysApply: true
description: "Endpoint routing patterns and request handling conventions"
lastUpdated: "2025-10-08"
dependencies: ["quality-standards", "api-patterns", "bun-runtime"]
---

# Endpoint Routing Rules

## 🔍 Code Searchability Patterns

### Find api-patterns Issues with ast-grep

```bash
# Find async function $NAME(request: Request, env: Env, requestId: string)
# Find return createJSONResponse($$$)
# Find return createErrorResponse($$$)
# Find generateRequestId()
# Find createLogger($$$)
ast-grep --pattern 'async function $NAME(request: Request, env: Env, requestId: string)' src/
ast-grep --pattern 'return createJSONResponse($$$)' src/
ast-grep --pattern 'return createErrorResponse($$$)' src/
ast-grep --pattern 'generateRequestId()' src/
ast-grep --pattern 'createLogger($$$)' src/
sg -p 'async' src/
sg -p 'return' src/
sg -p 'return' src/
sg -p 'generateRequestId()' src/
sg -p 'createLogger($$$)' src/
```

### api-patterns Discovery Commands

```bash
sg search "async function" src/api/
sg search "createJSONResponse" src/
sg search "generateRequestId" src/
sg search "createLogger" src/
```

### Search Examples

```bash
# Find all API endpoint handlers
sg search 'async' src/
# Find JSON response patterns
sg search 'return' src/
# Find request ID generation
sg search 'return' src/
# Find logging patterns
sg search 'generateRequestId()' src/
```
## Main Entry Point

All HTTP requests are handled in [src/index.ts](mdc:src/index.ts) via the `fetch()` handler.

## Request Flow Pattern

```typescript
import { generateRequestId, createOPTIONSResponse, createJSONResponse } from '../utils/request';
import { createLogger } from '../utils/logger';

1. Generate requestId: generateRequestId()
2. Parse URL: new URL(request.url)
3. Log request details with StructuredLogger
4. Handle CORS preflight: createOPTIONSResponse()
5. Route by pathname
6. Return response: createJSONResponse() (includes CORS)
```

## Endpoint Categories

### Core System Endpoints (4)

**Pattern:** Exact pathname match

```typescript
if (url.pathname === '/health') {
  // Health check - used by all dashboards
  // Returns: { status, version, timestamp, requestId, duration }
}

if (url.pathname === '/logs') {
  // Centralized logging - used by browser extension
  // POST: Receives log batches from extension
}

if (url.pathname === '/diagnostics') {
  // System diagnostics - used by setup wizard, health monitor
  // Returns: bindings status, KV status, last checks
}

if (url.pathname === '/system-status') {
  // Detailed status - used by dashboard stats
  // Returns: uptime, memory, KV records, health indicators
}
```

**Used By:** All dashboards, monitoring tools, browser extension

---

### BetTicker Endpoints (3+)

**Pattern:** Exact pathname or prefix match

```typescript
if (url.pathname === '/cloud/api/Manager/getBetTicker') {
  // Transparent proxy + KV interception
  // Handler: handleBetTickerInterception()
  // Location: src/interceptors/bet-ticker-sniffer.ts
  // Returns: Original API response (with side-effect KV storage)
}

if (url.pathname.startsWith('/interceptor/')) {
  // BetTicker history/analysis API
  // Handler: handleInterceptorAPI()
  // Routes:
  //   - /interceptor/history?limit=100
  //   - /interceptor/response?key=...
  //   - /interceptor/stats
}
```

**Used By:** Browser extension, all dashboards

**Documentation:** [docs/BET_TICKER_SNIFFER.md](mdc:docs/BET_TICKER_SNIFFER.md)

---

### MCP Protocol Endpoints (2+)

**Pattern:** Exact pathname or prefix match

```typescript
if (url.pathname === '/mcp') {
  // JSON-RPC 2.0 MCP protocol endpoint
  // Handler: handleMCPRequest()
  // Location: src/mcp/server.ts
  // Methods: initialize, tools/list, tools/call
}

if (url.pathname.startsWith('/tools/')) {
  // Intelligence tools API (13 tools)
  // Handler: handleMCPTools()
  // Routes:
  //   - /tools/getBettingExposure
  //   - /tools/getCLV
  //   - /tools/getSharpScore
  //   - /tools/getHoldPercentage
}
```

**Used By:** Claude Desktop, AI assistants, Dashboard Pro

**Documentation:** [docs/MCP_ENDPOINTS.md](mdc:docs/MCP_ENDPOINTS.md)

---

## Required Patterns

### 1. Request ID Tracking

**ALWAYS generate and use a request ID:**

```typescript
import { generateRequestId } from '../utils/request';
import { createLogger } from '../utils/logger';

const requestId = generateRequestId();
const logger = createLogger(request);
logger.info('request_received', { method, url });
```

**Use in responses:**
```typescript
import { createJSONResponse } from '../utils/request';

return createJSONResponse({ requestId, ...data });
```

---

### 2. CORS Headers

**ALWAYS include CORS headers for dashboard access:**

```typescript
import { CORS_HEADERS, createOPTIONSResponse, createJSONResponse } from '../utils/request';

// CORS headers available as constant
// No need to define inline
```

**Handle OPTIONS preflight:**
```typescript
if (request.method === 'OPTIONS') {
  return createOPTIONSResponse();
}
```

**Use in responses:**
```typescript
// Automatic with createJSONResponse
return createJSONResponse({ data });

// Or manually
return new Response(data, { headers: { ...CORS_HEADERS } });
```

---

### 3. Error Handling

**Standardized error response:**

```typescript
import { createErrorResponse } from '../utils/request';
import { createLogger } from '../utils/logger';

const logger = createLogger(request);

try {
  // Handler logic
} catch (error) {
  logger.error('handler_failed', {
    errorType: error instanceof Error ? error.name : 'Unknown'
  }, error as Error);

  return createErrorResponse(
    error instanceof Error ? error.message : 'Unknown error',
    500,
    'HANDLER_ERROR',
    requestId
  );
}
```

---

### 4. Performance Logging

**Log request duration:**

```typescript
import { performanceTimer } from '../utils/logger';

const logger = createLogger(request);
const timer = performanceTimer(logger, 'request_handler');

// ... handle request

timer.end({ requestId, statusCode: 200 });
```

---

## Handler Functions

### Pattern: Separate Functions for Complex Routes

```typescript
import { createJSONResponse, createErrorResponse, generateRequestId } from '../utils/request';
import { createLogger } from '../utils/logger';

// In main fetch handler:
if (url.pathname === '/diagnostics') {
  return handleDiagnostics(request, env, ctx);
}

// Separate handler function:
async function handleDiagnostics(
  request: Request,
  env: Env,
  ctx: ExecutionContext
): Promise<Response> {
  const requestId = generateRequestId();
  const logger = createLogger(request);

  try {
    logger.info('diagnostics_started', { requestId });
    // Handler logic
    return createJSONResponse({ data, requestId });
  } catch (error) {
    logger.error('diagnostics_failed', { requestId }, error as Error);
    return createErrorResponse('Diagnostics failed', 500, 'DIAGNOSTICS_ERROR', requestId);
  }
}
```

**Current handlers in [src/index.ts](mdc:src/index.ts):**
- `handleMCPTools()` - Routes to intelligence tools
- `handleDiagnostics()` - System diagnostics
- `handleLogs()` - Log retrieval
- `handleSystemStatus()` - Detailed status
- `handleInterceptorAPI()` - BetTicker history/analysis

---

## Integration Points

### Dashboard Hub Integration

**Location:** [dashboards/index.html](mdc:dashboards/index.html)

**Connected Endpoints:**
```javascript
const WORKER_URL = 'https://betting-brain-v3.nolarose1968-806.workers.dev';

// System status
fetch(`${WORKER_URL}/health`)

// Data count and last update
fetch(`${WORKER_URL}/interceptor/history?limit=100`)
```

**Auto-refresh:** 30 seconds

---

### Browser Extension Integration

**Location:** [browser-extension/](mdc:browser-extension/)

**Connected Endpoints:**
```javascript
// Log forwarding (background.js)
fetch(`${WORKER_URL}/logs`, {
  method: 'POST',
  body: JSON.stringify({ logs, sessionId })
})

// BetTicker interception (content.js)
fetch(`${WORKER_URL}/cloud/api/Manager/getBetTicker`, {
  method: 'POST',
  body: originalRequestBody
})
```

---

## Queue & Cron Integration

### Queue Consumers

**Handler:** `async queue(batch: MessageBatch, env: Env, ctx: ExecutionContext)`

**Routes:**
```typescript
if (batch.queue === 'line-ingress') {
  await handleLineIngress(message, env, ctx);
}
if (batch.queue === 'steam-webhook') {
  await handleSteamWebhook(message, env, ctx);
}
```

**Location:** [src/queues/](mdc:src/queues/)

---

### Scheduled Jobs

**Handler:** `async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext)`

**Routes:**
```typescript
if (event.cron === '0 * * * *') {
  // Hourly sharp calculation
  await handleSharpCalculation(env, ctx);
}
if (event.cron === '*/30 * * * * *') {
  // 30-second exposure calculation (actually every minute due to CF limitations)
  await handleExposureCalculation(env, ctx);
}
```

**Location:** [src/schedules/](mdc:src/schedules/)

**Documentation:** [docs/DATABASE_CRON_VERIFICATION.md](mdc:docs/DATABASE_CRON_VERIFICATION.md)

---

## Adding New Endpoints

### 1. Core/System Endpoint

**Add to main fetch handler:**
```typescript
import { generateRequestId } from '../utils/request';
import { createLogger } from '../utils/logger';

const requestId = generateRequestId();
const logger = createLogger(request);

if (url.pathname === '/my-endpoint') {
  logger.info('endpoint_accessed', { endpoint: '/my-endpoint', requestId });
  return handleMyEndpoint(request, env, ctx);
}
```

**Create handler function:**
```typescript
import {
  generateRequestId,
  createJSONResponse,
  createErrorResponse
} from '../utils/request';
import { createLogger } from '../utils/logger';

async function handleMyEndpoint(
  request: Request,
  env: Env,
  ctx: ExecutionContext
): Promise<Response> {
  const requestId = generateRequestId();
  const logger = createLogger(request);

  try {
    logger.info('handler_started', { requestId });
    // Your logic here
    return createJSONResponse({ data, requestId });
  } catch (error) {
    logger.error('handler_failed', { requestId }, error as Error);
    return createErrorResponse(
      error instanceof Error ? error.message : 'Unknown error',
      500,
      'HANDLER_ERROR',
      requestId
    );
  }
}
```

---

### 2. Intelligence Tool Endpoint

**Add to handleMCPTools switch:**
```typescript
case 'getMyTool':
  return getMyTool(request, env);
```

**Create tool file:**
- Location: [src/tools/intelligence/getMyTool.ts](mdc:src/tools/intelligence/)
- Export: `export async function getMyTool(request: Request, env: Env): Promise<Response>`

**Add to MCP tools list:**
- Location: [src/mcp/tools.ts](mdc:src/mcp/tools.ts)
- Add tool definition with schema

---

### 3. MCP Handler

**Create handler:**
- Location: [src/mcp/handlers/myHandler.ts](mdc:src/mcp/handlers/)
- Export function matching tool name

**Register in toolRegistry:**
- Location: [src/mcp/toolRegistry.ts](mdc:src/mcp/toolRegistry.ts)
- Add case statement

**Documentation:** [docs/MCP_ENDPOINTS.md](mdc:docs/MCP_ENDPOINTS.md)

---

## Performance Expectations

| Endpoint Type | Expected Response Time | Complexity |
|--------------|----------------------|------------|
| `/health` | 5-20ms | Low |
| `/interceptor/history` | 50-300ms | Medium |
| `/mcp` (tools/list) | 20-100ms | Low |
| `/mcp` (tools/call) | 100-500ms | High |
| `/tools/*` | 50-150ms | Low-Medium |

**CPU Limit:** 50ms per request (from wrangler.toml)

---

## Testing Endpoints

### Local Development

```bash
# Start worker
bun run dev

# Test health
curl http://localhost:8787/health

# Test with request ID
curl -H "X-Request-ID: test123" http://localhost:8787/diagnostics

# Test MCP
curl -X POST http://localhost:8787/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
```

### Production

```bash
# Deploy
wrangler deploy --env production

# Test
curl https://betting-brain-v3.nolarose1968-806.workers.dev/health

# Monitor
wrangler tail --env production
```

---

## Common Pitfalls

### ❌ DON'T

```typescript
// No CORS headers
return new Response(JSON.stringify(data));

// No request ID tracking
console.log('Request received');

// Inline CORS headers
const corsHeaders = { 'Access-Control-Allow-Origin': '*' };

// Manual request ID
const requestId = Date.now().toString(36);

// No error handling
const result = await riskyOperation();
return new Response(JSON.stringify(result));
```

### ✅ DO

```typescript
import {
  generateRequestId,
  createJSONResponse,
  createErrorResponse,
  CORS_HEADERS
} from '../utils/request';
import { createLogger } from '../utils/logger';

// With proper utilities
const requestId = generateRequestId();
const logger = createLogger(request);
logger.info('request_received', { requestId });

// With error handling
try {
  const result = await riskyOperation();
  return createJSONResponse({ requestId, result });
} catch (error) {
  logger.error('operation_failed', { requestId }, error as Error);
  return createErrorResponse(
    error instanceof Error ? error.message : 'Unknown',
    500,
    'OPERATION_ERROR',
    requestId
  );
}
```

---

## Related Rules

- [Quality Standards](mdc:.cursor/rules/quality-standards.mdc) - Code quality standards ⭐ **NEW**
- [API Patterns](mdc:.cursor/rules/api-patterns.mdc) - API validation & error handling
- [Cloudflare Workers](mdc:.cursor/rules/cloudflare-workers.mdc) - Workers patterns
- [MCP Integration](mdc:.cursor/rules/mcp-integration.mdc) - MCP patterns

## Related Documentation

- **[docs/QUALITY_STANDARDS.md](mdc:docs/QUALITY_STANDARDS.md)** - Complete quality guide ⭐ **NEW**
- **[src/utils/request.ts](mdc:src/utils/request.ts)** - Request utilities ⭐ **NEW**
- **[src/utils/logger.ts](mdc:src/utils/logger.ts)** - Logging utilities ⭐ **NEW**
- **[src/shared/constants.ts](mdc:src/shared/constants.ts)** - All constants ⭐ **NEW**
- **[docs/ENDPOINT_DASHBOARD_INTEGRATION.md](mdc:docs/ENDPOINT_DASHBOARD_INTEGRATION.md)** - Complete endpoint guide
- **[docs/SYSTEM_INTEGRATION_MAP.md](mdc:docs/SYSTEM_INTEGRATION_MAP.md)** - System architecture

---

**Total Endpoints:** 10+ core endpoints + 13 MCP tools
**Status:** Production-ready with full CORS, error handling, and logging
**Last Updated:** 2025-10-08

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.