typescript-mcp — quality + safety report

In the Skillier index (secondsky__typescript-mcp) · scanned 2026-06-03 · engine: builtin+triage

A
Quality
92/100
Safety

1 heuristic flag to review

Heuristic flags from the builtin scanner, which is known to over-flag (it trips on legitimate env-reading integrations, security skills, and library .eval calls). This is NOT an authoritative malicious verdict — re-scan with SkillSpector for the authoritative result. Run the authoritative scan →

Skillproof quality grade A

📇 This skill is in the Skillier index (curated · deduped · quality-filtered). Install Skillier to route & load it into your AI client.

Quality notes

Skill is large (~4117 tokens)
medium · quality · body
→ Tighten to the essential procedure; move long reference material to linked files.

About this skill

MCP servers with TypeScript on Cloudflare Workers using @modelcontextprotocol/sdk. Use for API integrations, stateless tools, edge deployments, or encountering export syntax, schema validation, memory leak, CORS, auth errors.

📄 Read the SKILL.md
---
name: typescript-mcp
description: "MCP servers with TypeScript on Cloudflare Workers using @modelcontextprotocol/sdk. Use for API integrations, stateless tools, edge deployments, or encountering export syntax, schema validation, memory leak, CORS, auth errors."
license: MIT
metadata:
  version: 2.0.0
  last_updated: 2025-12-17
  optimization_date: 2025-12-17
  token_savings: ~55%
  sdk_version: "@modelcontextprotocol/sdk@1.22.0"
  platform: cloudflare-workers
  production_tested: true
  errors_prevented: 13
  keywords:
    - mcp
    - model context protocol
    - typescript mcp
    - cloudflare workers mcp
    - mcp server
    - mcp tools
    - mcp resources
    - mcp sdk
    - "@modelcontextprotocol/sdk"
    - hono mcp
    - streamablehttpservertransport
    - mcp authentication
    - mcp cloudflare
    - edge mcp server
    - serverless mcp
    - typescript mcp server
    - mcp api
    - llm tools
    - ai tools
    - cloudflare d1 mcp
    - cloudflare kv mcp
    - mcp testing
    - mcp deployment
    - wrangler mcp
    - export syntax error
    - schema validation error
    - memory leak mcp
    - cors mcp
    - rate limiting mcp
allowed-tools: [Read, Write, Edit, Bash, Grep, Glob]
---
# TypeScript MCP Server on Cloudflare Workers

Build production-ready Model Context Protocol (MCP) servers using TypeScript and deploy them on Cloudflare Workers. This skill covers the official `@modelcontextprotocol/sdk`, HTTP transport setup, authentication patterns, Cloudflare service integrations, and comprehensive error prevention.

---

## When to Use This Skill

Use this skill when:
- Building **MCP servers** to expose APIs, tools, or data to LLMs
- Deploying **serverless MCP endpoints** on Cloudflare Workers
- Integrating **external APIs** as MCP tools (REST, GraphQL, databases)
- Creating **stateless MCP servers** for edge deployment
- Exposing **Cloudflare services** (D1, KV, R2, Vectorize) via MCP protocol
- Implementing **authenticated MCP servers** with API keys, OAuth, or Zero Trust
- Building **multi-tool MCP servers** with resources and prompts
- Needing **production-ready templates** that prevent common MCP errors

**Do NOT use this skill when**:
- Building **Python MCP servers** (use FastMCP skill instead)
- Needing **stateful agents** with WebSockets (use Cloudflare Agents SDK)
- Wanting **long-running persistent agents** with SQLite storage (use Durable Objects)
- Building **local CLI tools** (use stdio transport, not HTTP)

---

## Secure Installation

MCP server packages grant tool access to LLMs — a compromised SDK can expose full system control. Verify packages before installing. Follow supply chain security best practices:

- **Block post-install scripts** — `npm config set ignore-scripts true` (or Bun: disabled by default)
- **Cooldown period** — Wait 7 days for new package versions to be vetted by the community
- **Audit before installing** — Run `socket package score npm <pkg>` or use `socket npm install <pkg>` to check packages

Load the `dependency-upgrade` skill for full security configuration including Socket CLI integration, cooldown setup, lockfile validation, and CI enforcement.

## Core Concepts

**MCP Protocol Components**:

1. **Tools** - Functions LLMs can invoke (Zod schemas, async handlers, external APIs)
2. **Resources** - Data exposure (URI-based: `config://app`, `user://{userId}`)
3. **Prompts** - Pre-configured templates for LLM interactions
4. **Completions** - Argument auto-complete (optional)

---

## Quick Start

### 1. Install Dependencies

```bash
bun add @modelcontextprotocol/sdk hono zod
bun add -d @cloudflare/workers-types wrangler typescript
```

### 2. Create Basic MCP Server

```typescript
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { Hono } from 'hono';
import { z } from 'zod';

const server = new McpServer({ name: 'my-mcp-server', version: '1.0.0' });

// Register a tool
server.registerTool(
  'echo',
  {
    description: 'Echoes back the input text',
    inputSchema: z.object({ text: z.string().describe('Text to echo') })
  },
  async ({ text }) => ({ content: [{ type: 'text', text }] })
);

// HTTP endpoint
const app = new Hono();

app.post('/mcp', async (c) => {
  const transport = new StreamableHTTPServerTransport({
    sessionIdGenerator: undefined,
    enableJsonResponse: true
  });

  // CRITICAL: Close transport to prevent memory leaks
  c.res.raw.on('close', () => transport.close());

  await server.connect(transport);
  await transport.handleRequest(c.req.raw, c.res.raw, await c.req.json());
  return c.body(null);
});

export default app;
```

### 3. Deploy

```bash
wrangler deploy
```

### 4. Use Production Templates

**For complete implementations**, copy from `templates/` directory:
- `templates/basic-mcp-server.ts` - Minimal working server
- `templates/tool-server.ts` - Multiple tools (API integrations, calculations)
- `templates/resource-server.ts` - Static and dynamic resources
- `templates/full-server.ts` - Complete server (tools + resources + prompts)
- `templates/authenticated-server.ts` - Production security with API key authentication
- `templates/wrangler.jsonc` - Cloudflare Workers configuration

---

## Authentication Patterns

**Quick Example** - API Key Authentication (Most Common):

```typescript
app.use('/mcp', async (c, next) => {
  const authHeader = c.req.header('Authorization');
  if (!authHeader?.startsWith('Bearer ')) {
    return c.json({ error: 'Unauthorized' }, 401);
  }

  const apiKey = authHeader.replace('Bearer ', '');
  const isValid = await c.env.MCP_API_KEYS.get(`key:${apiKey}`);
  if (!isValid) return c.json({ error: 'Invalid API key' }, 403);

  await next();
});
```

**For complete authentication guide**: Load `references/authentication-guide.md` when implementing production authentication. Covers 5 methods: API Key (recommended), Cloudflare Zero Trust Access, OAuth 2.0, JWT custom, and mTLS. Includes security best practices, testing strategies, and migration guides.

---

## Cloudflare Service Integration

**Quick Example** - D1 Database Tool:

```typescript
server.registerTool(
  'query-database',
  {
    description: 'Executes SQL query on D1 database',
    inputSchema: z.object({
      query: z.string(),
      params: z.array(z.union([z.string(), z.number()])).optional()
    })
  },
  async ({ query, params }, env) => {
    const result = await env.DB.prepare(query).bind(...(params || [])).all();
    return { content: [{ type: 'text', text: JSON.stringify(result.results, null, 2) }] };
  }
);
```

**Supported Services**: D1 (SQL Database), KV (Key-Value Store), R2 (Object Storage), Vectorize (Vector Database), Workers AI, Queues, Analytics Engine.

**For complete integration guide**: Load `references/cloudflare-integration.md` when integrating Cloudflare services. Includes setup, MCP tool examples, best practices, and advanced patterns (RAG systems, combining services).

---

## Testing Strategies

**Quick Testing Workflow**:

1. **Unit Tests** (Vitest): Test tool logic in isolation
2. **Integration Tests** (MCP Inspector): Test with `bunx @modelcontextprotocol/inspector`
3. **E2E Tests**: Test with real MCP clients

```bash
# Local dev
npm run dev

# Test with Inspector
bunx @modelcontextprotocol/inspector
```

**For complete testing guide**: Load `references/testing-guide.md` when writing tests. Covers unit testing with Vitest, integration testing with MCP Inspector, E2E testing, authentication testing, load testing with Artillery, mocking external APIs, and CI/CD testing patterns.

---

## Known Issues Prevention

This skill prevents **13 documented errors**. Here are the **top 5 most critical**:

### Issue #1: Export Syntax Issues (CRITICAL)
**Error**: `"Cannot read properties of undefined (reading 'map')"`
**Source**: honojs/hono#3955
**Prevention**:
```typescript
// ❌ WRONG                      // ✅ CORRECT
export default { fetch: app.fetch };    export default app;
```

### Issue #2: Unclosed Transport Connections
**Error**: Memory leaks, hanging connections
**Prevention**:
```typescript
app.post('/mcp', async (c) => {
  const transport = new StreamableHTTPServerTransport({...});
  c.res.raw.on('close', () => transport.close()); // CRITICAL
  // ... handle request
});
```

### Issue #3: Tool Schema Validation Failure
**Error**: `ListTools request handler fails to generate inputSchema`
**Source**: modelcontextprotocol/typescript-sdk#1028
**Prevention**: Pass Zod schema directly - SDK handles conversion automatically
```typescript
server.registerTool('tool', { inputSchema: z.object({...}) }, handler);
```

### Issue #4: Tool Arguments Not Passed to Handler
**Error**: Handler receives `undefined` arguments
**Source**: modelcontextprotocol/typescript-sdk#1026
**Prevention**: Use `z.infer<typeof schema>` for type-safe handler parameters

### Issue #5: CORS Misconfiguration
**Error**: Browser clients can't connect
**Prevention**:
```typescript
import { cors } from 'hono/cors';
app.use('/mcp', cors({ origin: ['http://localhost:3000'], allowMethods: ['POST', 'OPTIONS'] }));
```

**For complete error catalog**: Load `references/common-errors.md` when debugging. Covers all 13 errors with detailed solutions, root causes from GitHub issues, and debugging checklist.

---

## Deployment Workflow

**Quick Deployment**:

```bash
# Local development
npm run dev  # Server at http://localhost:8787/mcp

# Production
npm run build
wrangler deploy

# Specific environment
wrangler deploy --env production
```

**For complete deployment guide**: Load `references/deployment-guide.md` when setting up production. Covers environment setup (dev/staging/prod), multiple environments, custom domains, CI/CD with GitHub Actions, database migrations, monitoring & logs, rollback strategy, performance optimization, health checks, cost optimization, security checklist, and troubleshooting.

---

## Package Versions (Verified 2025-10-28)

```json
{
  "dependencies": {
    "@modelcontextprotocol/sdk": "^1.20.2",
    "@cloudflare/workers-types": "^4.20251011.0",
    "hono": "^4.10.1",
    "zod": "^4.1.12"
  },
  "devDependencies": {
    "@cloudflare/vitest-pool-workers": "^0.5.29",
    "vitest": "^3.0.0",
    "wrangler": "^4.43.0",
    "typescript": "^5.7.0"
  }
}
```

---

## When to Use Cloudflare Agents SDK Instead

Use **Cloudflare Agents MCP** when you need:
- **Stateful agents** with persistent storage (SQLite up to 1GB)
- **WebSocket support** for real-time bidirectional communication
- **Long-running sessions** with conversation history
- **Scheduled agent tasks** with Durable Objects alarms
- **Global distribution** with automatic state replication

Use **this skill (standalone TypeScript MCP)** when you need:
- **Stateless tools** and API integrations
- **Edge deployment** with minimal cold start latency
- **Simple authentication** (API keys, OAuth)
- **Pay-per-request pricing** (no Durable Objects overhead)
- **Maximum portability** (works on any platform, not just Cloudflare)

See `references/cloudflare-agents-vs-standalone.md` for detailed comparison.

---

## When to Load References

Load reference files when working on specific aspects of TypeScript MCP servers:

### authentication-guide.md
Load when:
- **Setup-based**: Implementing authentication for production MCP server
- **Method-based**: Choosing between API Key, OAuth 2.0, Zero Trust, JWT, or mTLS
- **Security-based**: Implementing rate limiting, API key rotation, audit logging
- **Testing-based**: Writing authentication tests (unit, integration, E2E)
- **Migration-based**: Upgrading from one auth method to another

### cloudflare-agents-vs-standalone.md
Load when:
- **Decision-based**: Choosing between standalone MCP and Cloudflare Agents SDK
- **Architecture-based**: Need stateful agents vs stateless tools
- **Cost-based**: Comparing pricing for low/high traffic scenarios
- **Feature-based**: Need WebSocke

… (truncated)
Scan or optimize your own skill →

Want a live grade + an embeddable README badge? Run your skill through the free scanner.

Graded independently by Skillproof — nothing to sell the author. Quality is mechanical + corpus-grounded; safety flags are heuristic (builtin+triage), not a malicious verdict.