agentleFS
brendadeeznuts1111brendadeeznuts1111/betting-brain-v3/.cursor/rules/mcp-integration.mdc

betting-brain-v3 / rules

Cursor rule8 starsChanged 14 months agoMITView on GitHub

MCP server integration patterns and conventions

  • Sends data out

The file

We split this mcp-integration.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:

    Error Handling: Always return isError: true for failures

    line 210
  2. Distinctive:

    Type Safety: Use TypeScript interfaces for args

    line 212
  3. Distinctive:

    Testing: Test with direct handler script first

    line 215
  4. Very specific:

    D1 Normalization: Always use normalizeD1Result() for type safety ⭐ NEW

    line 216

≈ “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
mcp-integration.mdc
---
version: "2.0.0"
globs: "src/mcp/**/*.ts"
alwaysApply: true
description: "MCP server integration patterns and conventions"
lastUpdated: "2025-10-08"
dependencies: ["quality-standards", "database-patterns", "api-patterns", "bun-runtime"]
---

# MCP Integration Rules

## 🔍 Code Searchability Patterns

### Find mcp-integration Issues with ast-grep

```bash
# Find export async function $NAME(params: $PARAMS, env: Env)
# Find MCPToolResult
# Find registerTool($$$)
# Find JSON-RPC
ast-grep --pattern 'export async function $NAME(params: $PARAMS, env: Env)' src/
ast-grep --pattern 'MCPToolResult' src/
ast-grep --pattern 'registerTool($$$)' src/
ast-grep --pattern 'JSON-RPC' src/
sg -p 'export' src/
sg -p 'MCPToolResult' src/
sg -p 'registerTool($$$)' src/
sg -p 'JSON-RPC' src/
```

### mcp-integration Discovery Commands

```bash
sg search "MCPToolResult" src/
sg search "registerTool" src/
sg search "JSON-RPC" src/
sg search "export async function" src/mcp/
```

### Search Examples

```bash
# Find MCP tool handlers
sg search 'export' src/
# Find tool registration
sg search 'MCPToolResult' src/
# Find JSON-RPC usage
sg search 'registerTool($$$)' src/
# Find MCP result types
sg search 'JSON-RPC' src/
```
## Overview

The MCP (Model Context Protocol) server provides **13 working tools** via JSON-RPC 2.0 endpoint at `/mcp`.

See [docs/MCP_INTEGRATION_STATUS.md](mdc:docs/MCP_INTEGRATION_STATUS.md) for complete status.

## Architecture

```
src/mcp/
├── server.ts           # JSON-RPC 2.0 request router
├── types.ts            # MCP protocol types
├── tools.ts            # Tool definitions and schemas
├── toolRegistry.ts     # Handler registry
└── handlers/           # Tool implementations (9 handlers)
    ├── steamMoves.ts
    ├── riskConcentration.ts
    ├── sharpActivity.ts
    ├── timeSeriesCLV.ts
    ├── enhancedSharpScore.ts
    ├── holdForecast.ts
    ├── handleAndHold.ts
    ├── customerVolume.ts
    └── timeSeriesAnalytics.ts
```

## Request Flow

```
POST /mcp → handleMCPRequest() [server.ts]
  ↓
Route by method:
  - initialize → Return capabilities
  - tools/list → Return tool definitions
  - tools/call → callTool() [toolRegistry.ts]
    ↓
Handler Function [handlers/*.ts]
    ↓
D1 Database Query
    ↓
MCPToolResult → JSON-RPC Response
```

## Adding a New Tool

### 1. Create Handler (`src/mcp/handlers/myTool.ts`)
```typescript
import type { MCPToolResult, MCPEnv } from '../types';
import { normalizeD1Result } from '../../utils/request';

interface MyToolArgs {
  param1: string;
  param2?: number;
}

interface TableRow {
  id: string;
  field: string;
  // ... other fields
}

export async function getMyTool(
  args: MyToolArgs,
  env: MCPEnv
): Promise<MCPToolResult> {
  // Validate args
  if (!args.param1) {
    return {
      content: [{ type: 'text', text: 'Error: param1 required' }],
      isError: true
    };
  }

  // Query database
  const result = await env.ANALYTICS.prepare(
    'SELECT * FROM table WHERE field = ?'
  ).bind(args.param1).all();

  // Normalize D1 results
  const data = normalizeD1Result<TableRow>(result);

  // Return formatted result
  return {
    content: [{
      type: 'text',
      text: JSON.stringify(data, null, 2)
    }]
  };
}
```

### 2. Register in `toolRegistry.ts`
```typescript
import { getMyTool } from './handlers/myTool';

case 'getMyTool':
  return await getMyTool(args, env);
```

### 3. Define in `tools.ts`
```typescript
{
  name: 'getMyTool',
  description: 'Clear description of what this tool does',
  inputSchema: {
    type: 'object',
    properties: {
      param1: { type: 'string', description: '...' },
      param2: { type: 'number', description: '...', optional: true }
    },
    required: ['param1']
  }
}
```

## Testing MCP Tools

### Direct Handler Testing (Fastest)
```bash
bun scripts/test-handlers-direct.ts
```

### HTTP Testing
```bash
# Start server
bun run dev

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

## Database Tables

MCP tools use these D1 tables:
- `sharp_indicators` - Customer profiling
- `line_movements` - Line changes
- `bet_history` - Historical bets ✨ NEW
- `hold_tracking` - Hold % history ✨ NEW
- `exposure_tracking` - Real-time exposure

See [migrations/0003_mcp_tables.sql](mdc:migrations/0003_mcp_tables.sql) for MCP-specific schema.

## Tool Categories

### Intelligence (4 tools)
- getBettingExposure, getCLV, getHoldPercentage, getSharpScore

### Live Betting (3 tools)
- getSteamMoves, getRiskConcentration, getSharpActivity

### Analytics (6 tools)
- getTimeSeriesCLV, getEnhancedSharpScore, getHoldForecast
- getHandleAndHold, getCustomerVolume, getTimeSeriesAnalytics

## Best Practices

1. **Error Handling:** Always return `isError: true` for failures
2. **Validation:** Validate all args before database queries
3. **Type Safety:** Use TypeScript interfaces for args
4. **Performance:** Optimize queries (target < 500ms)
5. **Documentation:** Clear descriptions in tool definitions
6. **Testing:** Test with direct handler script first
7. **D1 Normalization:** Always use `normalizeD1Result()` for type safety ⭐ **NEW**

---

## Related Rules

- [Quality Standards](mdc:.cursor/rules/quality-standards.mdc) - Code quality standards ⭐ **NEW**
- [Database Patterns](mdc:.cursor/rules/database-patterns.mdc) - Database best practices
- [API Patterns](mdc:.cursor/rules/api-patterns.mdc) - API design patterns
- [Cloudflare Workers](mdc:.cursor/rules/cloudflare-workers.mdc) - Workers 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 & D1 utilities ⭐ **NEW**
- [docs/MCP_TESTING_GUIDE.md](mdc:docs/MCP_TESTING_GUIDE.md) - Testing guide
- [docs/MCP_ENDPOINTS.md](mdc:docs/MCP_ENDPOINTS.md) - Complete API reference
- [src/mcp/](mdc:src/mcp/) - MCP server implementation

---

**Status:** Production-ready MCP server
**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.