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

推荐订阅源

Help Net Security
Help Net Security
www.infosecurity-magazine.com
www.infosecurity-magazine.com
SecWiki News
SecWiki News
Webroot Blog
Webroot Blog
AI
AI
S
Secure Thoughts
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Cloudbric
Cloudbric
Hacker News - Newest:
Hacker News - Newest: "LLM"
T
The Exploit Database - CXSecurity.com
Latest news
Latest news
N
News and Events Feed by Topic
Simon Willison's Weblog
Simon Willison's Weblog
Scott Helme
Scott Helme
S
Schneier on Security
H
Hacker News: Front Page
Forbes - Security
Forbes - Security
T
Troy Hunt's Blog
Know Your Adversary
Know Your Adversary
S
Security Affairs
V
Visual Studio Blog
Stack Overflow Blog
Stack Overflow Blog
博客园_首页
腾讯CDC
GbyAI
GbyAI
有赞技术团队
有赞技术团队
Last Week in AI
Last Week in AI
N
News and Events Feed by Topic
WordPress大学
WordPress大学
The Register - Security
The Register - Security
Engineering at Meta
Engineering at Meta
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Cisco Talos Blog
Cisco Talos Blog
人人都是产品经理
人人都是产品经理
大猫的无限游戏
大猫的无限游戏
Recent Announcements
Recent Announcements
V
V2EX
S
Securelist
Security Archives - TechRepublic
Security Archives - TechRepublic
B
Blog RSS Feed
PCI Perspectives
PCI Perspectives
Security Latest
Security Latest
I
InfoQ
I
Intezer
L
LangChain Blog
雷峰网
雷峰网
NISL@THU
NISL@THU
博客园 - 【当耐特】
Microsoft Azure Blog
Microsoft Azure Blog
阮一峰的网络日志
阮一峰的网络日志

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
Building Custom MCP Servers: A Developer's Guide to Production-Grade AI Agent Tools
The Daily Ag · 2026-05-05 · via DEV Community

The Model Context Protocol (MCP) has become the default standard for connecting AI agents to external tools and APIs. Governed by the Linux Foundation since early 2025 and adopted by OpenAI, Anthropic, Microsoft, and Vercel, MCP is the USB-C port of the AI ecosystem — one protocol that lets any LLM application talk to any tool server.

But there's a gap between reading the spec and building something that works reliably in production. I've spent the last few months building MCP servers for production agent workflows, and this guide captures the patterns that actually matter.

If you've read the "6 Agent Gateway Platforms" roundups, you know which MCP servers to consume. This is the guide for when you need to build one yourself.

What We're Building

By the end of this guide, you'll have built a production-ready MCP server that:

  • Exposes typed tools with JSON Schema validation
  • Uses Streamable HTTP transport (the 2026 recommended standard)
  • Handles errors gracefully with structured responses
  • Includes proper authentication for sensitive operations
  • Is testable with the MCP Inspector

Let's start with the foundation.

Architecture: The Three MCP Building Blocks

Before writing code, understand what your server can expose. MCP defines three primitives:

Feature What It Does Who Controls It
Tools Functions the AI model calls (write, compute, act) Model decides when to invoke
Resources Read-only data (files, DB schemas, API docs) Application retrieves and provides
Prompts Pre-built templates for common workflows User triggers explicitly

For a tool server — the most common production pattern — you'll focus on tools. Resources and prompts are optional but useful for providing context and guiding the model's behavior.

Setting Up a TypeScript MCP Server

The official TypeScript SDK is the most widely adopted way to build MCP servers. It's what Claude Desktop, Cursor, and Windsurf use internally.

// server.ts
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";

// Define a tool with Zod validation
const CodeReviewInput = z.object({
  repoPath: z.string().min(1, "Repository path is required"),
  prNumber: z.number().int().positive("PR number must be positive"),
  strictness: z.enum(["basic", "standard", "deep"]).default("standard"),
});

type CodeReviewInput = z.infer<typeof CodeReviewInput>;

// Server instance
const server = new Server(
  {
    name: "code-review-mcp",
    version: "1.0.0",
  },
  {
    capabilities: {
      tools: {},
    },
  }
);

// Tool registration
server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [
    {
      name: "review_pull_request",
      description:
        "Perform a code review on a pull request at the given path with configurable strictness",
      inputSchema: {
        type: "object",
        properties: {
          repoPath: {
            type: "string",
            description: "Absolute path to the local repository",
          },
          prNumber: {
            type: "number",
            description: "Pull request number to review",
          },
          strictness: {
            type: "string",
            enum: ["basic", "standard", "deep"],
            description: "How thorough the review should be",
          },
        },
        required: ["repoPath", "prNumber"],
      },
    },
  ],
}));

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name === "review_pull_request") {
    const args = CodeReviewInput.parse(request.params.arguments);

    try {
      const review = await performReview(args.repoPath, args.prNumber, args.strictness);
      return {
        content: [
          {
            type: "text",
            text: JSON.stringify(review, null, 2),
          },
        ],
      };
    } catch (error) {
      return {
        content: [
          {
            type: "text",
            text: `Review failed: ${error instanceof Error ? error.message : "Unknown error"}`,
          },
        ],
        isError: true,
      };
    }
  }

  throw new Error(`Unknown tool: ${request.params.name}`);
});

// Start with stdio transport (for local development)
const transport = new StdioServerTransport();
await server.connect(transport);

Enter fullscreen mode Exit fullscreen mode

This is the skeleton. Every MCP server follows this pattern: declare capabilities, define tool schemas, implement handlers, connect a transport.

Writing Tools That Agents Actually Use Well

The biggest mistake I see in MCP server designs is writing tools the way you'd write REST endpoints for other developers. Agents don't read documentation the way humans do. Your tool names, descriptions, and schemas need to be optimized for an LLM to discover and use correctly.

Naming Conventions

Use descriptive, action-oriented names:

  • Good: search_codebase, create_jira_ticket, deploy_to_staging
  • Bad: exec, run, helper, util

Descriptions That Work

Your tool description is the agent's documentation. Be explicit about when to use it, what it does, and edge cases.

{
  name: "deploy_service",
  description:
    "Deploy a service to the staging environment. Use when the user asks to deploy, push to staging, or test a deployment. Does NOT deploy to production — use deploy_to_production for that. Requires the service to have passed CI checks.",
}

Enter fullscreen mode Exit fullscreen mode

Input Schema Design

Keep required parameters minimal. Agents get confused by complex schemas with many required fields. Use sensible defaults wherever possible.

{
  inputSchema: {
    type: "object",
    properties: {
      serviceName: {
        type: "string",
        description: "Name of the service to deploy (e.g., 'api-gateway', 'worker')",
      },
      version: {
        type: "string",
        description: "Semantic version to deploy. If omitted, uses the latest built version.",
      },
      region: {
        type: "string",
        enum: ["us-west-2", "us-east-1", "eu-west-1"],
        description: "Target region. Defaults to us-west-2.",
      },
    },
    required: ["serviceName"],
  },
}

Enter fullscreen mode Exit fullscreen mode

One required field, optional parameters with clear defaults. The agent can succeed with minimal information and ask for more when needed.

Streamable HTTP: The Production Transport

Stdio transport is fine for local development (Claude Desktop, VS Code), but for production deployments you need HTTP. In 2026, Streamable HTTP has replaced Server-Sent Events (SSE) as the recommended standard.

// http-server.ts
import express from "express";
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";

const app = express();
app.use(express.json());

const mcpServer = new Server(
  { name: "production-mcp", version: "2.0.0" },
  { capabilities: { tools: {} } }
);

// Register tools (same as before)
mcpServer.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [
    // ... tool definitions
  ],
}));

// HTTP endpoint
app.post("/mcp", async (req, res) => {
  const transport = new StreamableHTTPServerTransport({
    sessionId: req.headers["mcp-session-id"] as string | undefined,
  });

  transport.onerror = (error) => {
    console.error("Transport error:", error);
  };

  await transport.handleRequest(req.body, req.headers, res);

  if (transport.sessionId) {
    res.setHeader("mcp-session-id", transport.sessionId);
  }
});

app.listen(3000, () => {
  console.log("MCP server listening on port 3000");
});

Enter fullscreen mode Exit fullscreen mode

The key advantage of Streamable HTTP over SSE is that connections are short-lived and stateless. Each request-response pair is independent, making it trivial to deploy behind load balancers and auto-scaling groups.

Testing with MCP Inspector

The MCP Inspector is the Postman of the MCP world. Run it against your server during development to validate your tool schemas and responses before any agent touches them:

npx @modelcontextprotocol/inspector node dist/server.js

Enter fullscreen mode Exit fullscreen mode

For HTTP servers:

npx @modelcontextprotocol/inspector http://localhost:3000/mcp

Enter fullscreen mode Exit fullscreen mode

This gives you a web UI where you can browse available tools and their schemas, execute tools with custom parameters, inspect raw JSON-RPC messages, and validate error handling paths.

Always run your tools through the Inspector before deploying. I've caught more schema bugs in the Inspector than in actual agent conversations.

Production Security Patterns

MCP's security model is intentionally permissive at the protocol level — the host application implements the guardrails.

Tool-Level Approval Gates

For sensitive operations, add an approval layer:

const sensitiveTools = ["delete_resource", "modify_production_config"];

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (sensitiveTools.includes(request.params.name)) {
    return {
      content: [
        {
          type: "text",
          text: `This operation requires approval. Please confirm by calling approve_operation with session ID.`,
        },
      ],
      isError: false,
    };
  }

  // Normal tool handling...
});

Enter fullscreen mode Exit fullscreen mode

Input Validation with Zod

Never trust the model's arguments. Even well-behaved agents can hallucinate parameter shapes:

const args = z
  .object({
    email: z.string().email(),
    template: z.string().min(1).max(100),
    variables: z.record(z.string()),
  })
  .strict()
  .parse(request.params.arguments);

Enter fullscreen mode Exit fullscreen mode

Rate Limiting and Quotas

MCP servers don't have built-in rate limiting — add it yourself:

import { rateLimit } from "express-rate-limit";

const limiter = rateLimit({
  windowMs: 60 * 1000,
  max: 100,
});

app.use("/mcp", limiter);

Enter fullscreen mode Exit fullscreen mode

Deployment Options

Approach Best For Transport
Local stdio Development, personal tools stdio
Docker + reverse proxy Internal team tools Streamable HTTP
Vercel (via @vercel/mcp-adapter) Serverless, public endpoints Streamable HTTP
Azure Container Apps Enterprise, Microsoft ecosystem Streamable HTTP
Kubernetes Multi-region, high-scale Streamable HTTP

The Full Picture: Where MCP Servers Fit

MCP servers are the tool layer in a larger agent architecture. You build servers that encapsulate specific capabilities — a Jira server, a GitHub server, a database query server — and an orchestrator like Nebula routes the right server to the right agent based on the user's intent.

Debugging Common Issues

  • Schema mismatches: Validate with Zod, return descriptive errors
  • Missing descriptions: Write descriptions that specify when (and when not) to use the tool
  • State assumptions: Make tools stateless — accept all needed context in arguments
  • Timeout failures: Return an operation ID immediately, provide a status-check tool

Key Takeaways

  • MCP is the standard for AI agent tooling in 2026
  • Build tools optimized for agents, not humans
  • Use Streamable HTTP for production
  • Always validate inputs with Zod
  • Test every tool with MCP Inspector
  • MCP servers are the tool layer; orchestrators like Nebula handle routing and state