typescript-mcp
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.
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**: LRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.