Claude
Skills
Sign in
Back

typescript-mcp

Included with Lifetime
$97 forever

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.

Backend & APIsscripts

What this skill does

# 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**: L

Related in Backend & APIs