惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Security @ Cisco Blogs
罗磊的独立博客
宝玉的分享
宝玉的分享
Last Week in AI
Last Week in AI
T
The Blog of Author Tim Ferriss
美团技术团队
T
Tailwind CSS Blog
博客园 - 三生石上(FineUI控件)
博客园 - Franky
G
Google Developers Blog
Jina AI
Jina AI
Stack Overflow Blog
Stack Overflow Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
V
Visual Studio Blog
腾讯CDC
S
SegmentFault 最新的问题
Recent Announcements
Recent Announcements
博客园 - 叶小钗
Microsoft Security Blog
Microsoft Security Blog
雷峰网
雷峰网
L
LangChain Blog
Vercel News
Vercel News
Forbes - Security
Forbes - Security
PCI Perspectives
PCI Perspectives
N
News | PayPal Newsroom
S
Security Affairs
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - 司徒正美
J
Java Code Geeks
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Hacker News: Ask HN
Hacker News: Ask HN
Schneier on Security
Schneier on Security
A
About on SuperTechFans
Attack and Defense Labs
Attack and Defense Labs
Google Online Security Blog
Google Online Security Blog
aimingoo的专栏
aimingoo的专栏
MongoDB | Blog
MongoDB | Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
Cloudbric
Cloudbric
B
Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Proofpoint News Feed
D
DataBreaches.Net
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
B
Blog RSS Feed
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
N
News and Events Feed by Topic

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Build your first MCP server in TypeScript: the 2026 setup that takes 30 minutes.
GDS K S · 2026-05-27 · via DEV Community

Build your first MCP server in TypeScript: the 2026 setup that takes 30 minutes.

I had Claude Desktop open. I needed it to query a local SQLite database without copy-pasting schema dumps into the chat. Thirty minutes later I had a working MCP server. Here is the exact path I took, stripped of dead ends.

TL;DR

Step What you build Time
Project setup npm project, tsconfig, SDK install 5 min
First tool Structured input, structured output 10 min
First resource Read-only data the model can request 8 min
Connect Claude Desktop Config file, restart, verify 5 min
Common pitfalls Avoid the three bugs that kill every first attempt 2 min

What MCP actually is

Model Context Protocol is a standard for connecting AI models to external data and tools. The model issues requests, your server handles them, and the results come back in a format the model understands. That is the whole idea.

Before MCP, every tool integration was custom. OpenAI had function calling. Anthropic had tool use. Cursor had its own plugin format. MCP standardizes the wire protocol so you write one server and any compliant client can call it, whether that is Claude Desktop, Cursor, or a client you build yourself.

The three primitives you care about:

  • Resources: read-only data the model can fetch, like files or database rows.
  • Tools: functions the model can call with arguments, like running a query or sending a request.
  • Prompts: reusable prompt templates the client can surface to the user.

This tutorial covers tools and resources. Prompts follow the same pattern and you will not need them for most servers.

1. Project setup

Node 18 or higher required. Check with node --version.

mkdir my-mcp-server && cd my-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node
mkdir src
touch src/index.ts

Enter fullscreen mode Exit fullscreen mode

The SDK package is @modelcontextprotocol/sdk. The version on npm as of May 2026 is 1.11.x. Zod handles schema validation for tool inputs.

Update package.json with these fields:

{
  "type": "module",
  "scripts": {
    "build": "tsc",
    "start": "node build/index.js"
  }
}

Enter fullscreen mode Exit fullscreen mode

Create tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "Node16",
    "moduleResolution": "Node16",
    "outDir": "./build",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

Enter fullscreen mode Exit fullscreen mode

2. Implementing a tool

A tool is a function the model can call. You define its name, description, input schema, and handler. The model reads the description and schema to decide when and how to call it.

Here is a complete server with one tool that converts a hex color to RGB:

// src/index.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({
  name: "color-tools",
  version: "1.0.0",
});

server.tool(
  "hex_to_rgb",
  "Convert a hex color string to RGB components. Input must include the leading #.",
  {
    hex: z.string().regex(/^#[0-9a-fA-F]{6}$/, "Must be a 6-digit hex color, e.g. #ff5733"),
  },
  async ({ hex }) => {
    const r = parseInt(hex.slice(1, 3), 16);
    const g = parseInt(hex.slice(3, 5), 16);
    const b = parseInt(hex.slice(5, 7), 16);
    return {
      content: [
        {
          type: "text",
          text: JSON.stringify({ hex, r, g, b }),
        },
      ],
    };
  },
);

const transport = new StdioServerTransport();
await server.connect(transport);

Enter fullscreen mode Exit fullscreen mode

Three things to notice:

The description string is what the model reads to decide whether to call the tool. Write it as plainly as you would write a JSDoc comment for a teammate. Vague descriptions produce missed calls or wrong inputs.

The second argument to server.tool() is the description. The third is a Zod schema object. The SDK turns this into a JSON Schema that the client sends to the model. Keep schemas tight: required fields only, no optional fields that do not change the output.

The return value must have a content array. Each item has a type and a text (or data for binary). Return JSON as a string inside a text item. The model can parse it from there.

Build and test locally:

npm run build
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | node build/index.js

Enter fullscreen mode Exit fullscreen mode

You should see a JSON-RPC response listing hex_to_rgb. That confirms the server starts and responds to the list request.

3. Implementing a resource

Resources expose read-only data the model can pull on demand. A common use case: expose the schema of your local database so the model knows the table structure before writing a query.

Add this before the transport setup:

server.resource(
  "db-schema",
  "sqlite:///local.db",
  async (uri) => {
    // In a real server, read this from your database
    const schema = `
CREATE TABLE users (
  id INTEGER PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at INTEGER NOT NULL
);
CREATE TABLE orders (
  id INTEGER PRIMARY KEY,
  user_id INTEGER REFERENCES users(id),
  total_cents INTEGER NOT NULL,
  placed_at INTEGER NOT NULL
);
    `.trim();
    return {
      contents: [
        {
          uri: uri.href,
          text: schema,
          mimeType: "text/plain",
        },
      ],
    };
  },
);

Enter fullscreen mode Exit fullscreen mode

The first argument is the resource name. The second is the URI the client uses to request it. Pick a URI scheme that makes sense for your data: file, sqlite, https, or a custom scheme like myapp://.

Resources are pull-based. The model requests them when it decides it needs them. If you want data pushed into every conversation automatically, that is a different pattern (system prompt injection at the client level, not a resource).

4. Hooking it up to Claude Desktop

Build the project:

npm run build

Enter fullscreen mode Exit fullscreen mode

Open your Claude Desktop config file. On macOS:

~/Library/Application Support/Claude/claude_desktop_config.json

Enter fullscreen mode Exit fullscreen mode

On Windows:

%APPDATA%\Claude\claude_desktop_config.json

Enter fullscreen mode Exit fullscreen mode

Add your server to the mcpServers block:

{
  "mcpServers": {
    "color-tools": {
      "command": "node",
      "args": ["/absolute/path/to/my-mcp-server/build/index.js"]
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Use the absolute path. Relative paths fail silently, which is the single most common first-timer mistake. Restart Claude Desktop fully (quit from the menu bar, not just close the window). Open a new conversation. You should see a hammer icon in the input bar indicating tools are available. Type "convert #3b82f6 to RGB" and watch it call the tool.

For Cursor, the config lives at ~/.cursor/mcp.json and uses the same mcpServers JSON shape:

{
  "mcpServers": {
    "color-tools": {
      "command": "node",
      "args": ["/absolute/path/to/my-mcp-server/build/index.js"]
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

For a generic client or testing: the MCP Inspector from Anthropic runs tool calls through a web UI without configuring Claude Desktop.

npx @modelcontextprotocol/inspector node /absolute/path/to/build/index.js

Enter fullscreen mode Exit fullscreen mode

Open the Inspector UI at port 6274 and you can fire tool calls manually and inspect the raw JSON-RPC traffic.

5. Transport choice: stdio vs HTTP

The setup above uses stdio transport. The client starts your server as a child process and communicates over stdin/stdout. This works for local tools and is the path of least resistance for Claude Desktop and Cursor.

For a remote server that two or more clients share, you need HTTP transport. The SDK ships StreamableHttpServerTransport for this. You pair it with an HTTP framework (Hono, Express, Fastify) and handle sessions. That setup adds meaningful complexity and is worth a separate article. Start with stdio unless you are building a shared service from day one.

One rule that applies to both: never write to stdout with console.log in a stdio server. The MCP protocol uses stdout for JSON-RPC frames. A stray log line corrupts the framing and the client sees a parse error with no helpful message. Use console.error() for debugging output. Everything sent to stderr is safe.

6. Common pitfalls

The three mistakes I see in every first MCP server attempt:

Schema validation gaps break calls silently. If the model sends an input that does not match your Zod schema, the SDK rejects it with a generic error. The model may retry with the same bad input. Write the schema narrowly and add .describe() calls on each field to help the model understand what values are valid.

// add field-level descriptions so the model knows what to send
{
  hex: z.string()
    .regex(/^#[0-9a-fA-F]{6}$/)
    .describe("Six-digit hex color with leading #, e.g. #ff5733"),
}

Enter fullscreen mode Exit fullscreen mode

Error responses need the right shape. When your tool handler throws, return a structured error instead of letting the exception propagate:

async ({ hex }) => {
  try {
    const r = parseInt(hex.slice(1, 3), 16);
    // ... rest of handler
    return { content: [{ type: "text", text: JSON.stringify({ r, g, b }) }] };
  } catch (err) {
    return {
      content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : "unknown"}` }],
      isError: true,
    };
  }
}

Enter fullscreen mode Exit fullscreen mode

The isError: true flag tells the client the call failed, which surfaces properly in Claude Desktop rather than showing as a successful response with error text inside.

Resource URIs must be stable. If a client caches a resource URI and your server changes it on restart, the cached reference points nowhere. Treat resource URIs like public API paths: change them only when you intend a breaking change and version them if needed.

The bottom line

MCP is not a new protocol that requires learning a whole ecosystem. The SDK is thin. You write a handler function, attach a schema, return a content array. The hard part is designing the right tools: narrow enough to be reliable, broad enough to be useful. A tool that does one thing with a clear input schema outperforms a general-purpose tool with six optional fields every time.

Build the color tool above. Get it running in Claude Desktop. Then replace the hex conversion with whatever data or action you actually want to expose. The scaffolding is identical regardless of what the tool does.

What would you expose through an MCP server if you had it running today?


GDS K S · thegdsks.com · follow on X @thegdsks

The scaffolding is 30 minutes; the tool design is the actual work.
resource" in a monospace font. Cool teal and electric blue
palette, minimal, vector-clean, no faces, no logos, no text beyond the card
labels. Subtle grid overlay on the background.



Enter fullscreen mode Exit fullscreen mode