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

推荐订阅源

T
Tenable Blog
月光博客
月光博客
雷峰网
雷峰网
WordPress大学
WordPress大学
博客园 - 司徒正美
Last Week in AI
Last Week in AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Visual Studio Blog
H
Help Net Security
Engineering at Meta
Engineering at Meta
Google DeepMind News
Google DeepMind News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
S
Security @ Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
爱范儿
爱范儿
W
WeLiveSecurity
J
Java Code Geeks
Forbes - Security
Forbes - Security
H
Hacker News: Front Page
T
Threatpost
The Cloudflare Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
N
Netflix TechBlog - Medium
Latest news
Latest news
V2EX - 技术
V2EX - 技术
小众软件
小众软件
T
The Blog of Author Tim Ferriss
A
Arctic Wolf
B
Blog RSS Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
I
InfoQ
C
Check Point Blog
N
News | PayPal Newsroom
Cyberwarzone
Cyberwarzone
V
V2EX
TaoSecurity Blog
TaoSecurity Blog
P
Privacy & Cybersecurity Law Blog
Microsoft Security Blog
Microsoft Security Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
D
DataBreaches.Net
F
Fortinet All Blogs
阮一峰的网络日志
阮一峰的网络日志
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
IT之家
IT之家
K
Kaspersky official blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Google DeepMind News
Google DeepMind News
C
CXSECURITY Database RSS Feed - CXSecurity.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com

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 an MCP Server in Node.js & TypeScript: A Practical HazelJS Tutorial
Muhammad Ars · 2026-05-10 · via DEV Community

Expose your existing TypeScript classes to Cursor, Claude Desktop, and any other Model Context Protocol (MCP) client — without writing protocol code, without a heavy SDK, and without standing up a separate HTTP service.

This post walks through the hazeljs-mcp-starter example in this folder: a small but realistic task board MCP server, written in TypeScript, that you can run locally with node dist/main.js and immediately drop into your AI tooling. It is not another "hello world" — every pattern below is the same one you would use to ship an internal support agent, a runbook automation server, or an admin operations panel for your team.

By the end you will know:

  • What MCP actually is (and is not), at the wire level
  • Why a tiny abstraction like @hazeljs/mcp beats writing JSON-RPC by hand
  • How to define tools with @Tool() decorators in idiomatic TypeScript
  • How to wire the resulting server into Cursor and Claude Desktop
  • How to test it without an LLM in the loop
  • How to evolve from in-memory toy code to a production-grade tool server (validation, persistence, observability, security)

Source code: hazel-js/hazeljs-mcp-starter on GitHub. Clone it and follow along:

git clone git@github.com:hazel-js/hazeljs-mcp-starter.git
cd hazeljs-mcp-starter
npm install

1. What is the Model Context Protocol, really?

MCP is a small, open JSON-RPC 2.0 protocol for one job: letting an AI client (Cursor, Claude Desktop, an SDK, your own runner) discover and invoke tools and resources exposed by a server. The wire format is intentionally boring — newline-delimited JSON over stdio (or HTTP/SSE) — which is what makes it portable.

The methods you'll see in practice are:

Method Direction Purpose
initialize client → server Handshake; server returns name, version, capabilities
ping either Liveness check
tools/list client → server Server returns its tool catalog (with JSON Schema)
tools/call client → server Server runs a named tool with arguments

A tool, on the wire, is just a name + description + JSON Schema for inputs. When the model decides to call it, the client sends tools/call, the server runs the corresponding function, and the result comes back as a content block (typically { type: 'text', text: '...' }).

That is the entire surface area. Everything else — auth, persistence, validation, observability — is your application's job, exactly as it would be for any other JSON-RPC service. MCP is plumbing, not a framework.

Why the protocol is small (and why that matters)

Because MCP is so minimal, the same server that Cursor talks to today can be consumed tomorrow by Claude Desktop, an OpenAI client, your in-house agent runtime, or a bash one-liner. You write the business logic once and let the transport carry it. That is the central value proposition we'll lean on for the rest of the article.


2. Why use @hazeljs/mcp instead of writing the protocol by hand?

Spec-correct JSON-RPC + MCP is not hard, but it's repetitive: parsing newline-delimited frames, routing methods, mapping your domain types to JSON Schema, formatting error envelopes with the right code values, preserving this context across decorator-based handlers, and so on. @hazeljs/mcp does all of that in roughly 200 lines, with zero runtime dependencies, so you can drop it into any Node.js project without dragging in a transport SDK or an LLM client.

Concretely, the package gives you three pieces:

  1. HazelToolAdapter — a transport-agnostic adapter that maps Hazel-style ToolMetadata (what @Tool() produces) to MCP's McpToolDefinition and dispatches tools/call to the right method, with the original this binding intact.
  2. A request router — pure async function over McpRequest → McpResponse, easy to plug into stdio (provided), HTTP, or SSE.
  3. A stdio transportlistenStdio() wires the router to process.stdin / process.stdout and handles concurrent in-flight calls without head-of-line blocking.

It also pairs with @hazeljs/agent, which provides the @Tool() decorator and ToolRegistry. The registry is the same one Hazel agents use internally, so a tool you write for your agent is automatically MCP-ready without a second tool definition format.

If you already have a ToolRegistry running inside your agent, you do not need to redefine anything. The same registry instance can be passed to createMcpServer() to project that tool surface to MCP clients.


3. What the starter does (and why a task board?)

A task board has just enough domain logic to be non-trivial: state, IDs, validation, status transitions, filtering. Replace the in-memory store with Prisma, Redis, or your HTTP API and the MCP boundary stays identical. That is the lesson worth taking home.

The starter exposes four tools:

Tool Inputs Output Purpose
list_tasks status? ("open"/"done") { tasks: Task[] } List all tasks; optional status filter
add_task title (string) Task Create a new open task
complete_task task_id (string) Task Transition a task to done
board_stats (none) { open: number, done: number } Quick aggregate for the model

Implementation files (linked to GitHub):


4. Project layout

hazeljs-mcp-starter/
├── package.json
├── tsconfig.json
├── README.md
├── BLOG.md                ← you are here
└── src/
    ├── main.ts            ← MCP entrypoint
    └── agents/
        └── TaskBoardMcpAgent.ts

Enter fullscreen mode Exit fullscreen mode

A few things to notice:

  • Single TypeScript project, single output directory. No monorepo gymnastics; tsc -p tsconfig.json writes everything to dist/.
  • src/main.ts is intentionally tiny. All it does is build the registry, hand it to createMcpServer, and call listenStdio(). Tests should drive the agent class directly, not the transport.
  • No top-level reflect-metadata import. @Tool() does not need design-time type metadata; only experimentalDecorators is required. Keeping that out of the surface keeps the bundle tiny.

5. The agent class, decorator by decorator

Here is the heart of the starter. Each method has a one-to-one mapping to an MCP tool, with parameter metadata that becomes JSON Schema in tools/list.

import { Tool } from '@hazeljs/agent';

type TaskStatus = 'open' | 'done';

interface Task {
  id: string;
  title: string;
  status: TaskStatus;
  createdAt: string;
}

/**
 * In-memory task board exposed as MCP tools.
 * Replace the store with Prisma, Redis, or your API — the @Tool surface stays the same.
 */
export class TaskBoardMcpAgent {
  private tasks: Task[] = [];
  private nextId = 1;

  @Tool({
    name: 'list_tasks',
    description: 'List tasks. Optionally filter by status (open or done).',
    parameters: [
      {
        name: 'status',
        type: 'string',
        description: 'Optional filter: "open" or "done"',
        required: false,
      },
    ],
  })
  async listTasks(input: Record<string, unknown>): Promise<{ tasks: Task[] }> {
    const filter = typeof input.status === 'string' ? input.status.toLowerCase() : undefined;
    const tasks =
      filter === 'open' || filter === 'done'
        ? this.tasks.filter((t) => t.status === filter)
        : [...this.tasks];
    return { tasks };
  }

Enter fullscreen mode Exit fullscreen mode

Full file on GitHub: src/agents/TaskBoardMcpAgent.ts

A few design choices worth explaining:

name is decoupled from the method name. listTasks (camelCase) is your TypeScript ergonomics; list_tasks (snake_case) is what the model sees. Keep the model-facing names short, lowercase, and verb-led — they show up in tool palettes and prompts.

description is prompt engineering. The LLM uses descriptions to decide whether to call your tool. "List tasks. Optionally filter by status" is much more useful than "List tasks." Add expected formats and edge cases ("Returns an empty array when no tasks exist"), but stay terse. A long description bloats every tool-routing prompt.

Parameters become a JSON Schema object. Each entry maps directly to a property under inputSchema.properties, with required: true lifting the name into inputSchema.required. Optional fields are declared as required: false and omitted from the required list. The model receives the full schema in tools/list and constructs valid arguments.

Inputs are Record<string, unknown>, not typed at compile time. That is the trade-off of working with an LLM: you cannot trust the shape, you must validate at runtime. We do exactly that with typeof input.status === 'string'. For larger tools, switch to a runtime validator (zod, ajv, valibot) — the package supports schema on @Tool() for Zod-first definitions.

Errors are thrown. When add_task receives an empty title we throw, and the MCP transport converts the exception into a -32603 INTERNAL_ERROR JSON-RPC response. The client surfaces that to the model, which can then retry with a corrected payload. For expected validation failures consider returning { ok: false, error: '...' } instead — that lets you keep HTTP-style semantics in the JSON body and avoids polluting your error logs.


6. The entrypoint: from class to wire

src/main.ts is deliberately five lines of "real" work:

/**
 * MCP entrypoint — started by Cursor / Claude Desktop via STDIO.
 * Build first: npm run build → run dist/main.js
 */
import { ToolRegistry } from '@hazeljs/agent';
import { createMcpServer } from '@hazeljs/mcp';

import { TaskBoardMcpAgent } from './agents/TaskBoardMcpAgent';

const registry = new ToolRegistry();
registry.registerAgentTools('taskboard', new TaskBoardMcpAgent());

const server = createMcpServer({
  name: 'hazeljs-mcp-starter-taskboard',
  version: '1.0.0',
  toolRegistry: registry,
});

server.listenStdio();

Enter fullscreen mode Exit fullscreen mode

What happens, step by step:

  1. new ToolRegistry() creates an empty store of name → ToolMetadata.
  2. registerAgentTools('taskboard', new TaskBoardMcpAgent()) reads decorator metadata off the class, creates fully-qualified entries (taskboard.list_tasks, …) for agent-to-agent dispatch, and keeps the short name ("list_tasks") that MCP clients will see.
  3. createMcpServer(...) snapshots the registry into a HazelToolAdapter, builds the JSON-RPC router, and returns an object with listenStdio() and listTools().
  4. server.listenStdio() attaches the router to process.stdin / process.stdout using a line-buffered reader. From this point forward, the process is a long-lived MCP child.

A subtle point: the registry is snapshotted at server-create time. If you add tools after createMcpServer() they will not show up. That is by design — MCP supports a listChanged capability for dynamic catalogs, but most servers do not need it, and a stable snapshot keeps the adapter simple.


7. The wire protocol, end to end

For an add_task call the conversation looks like this (one JSON object per line, both directions):

Client → server: handshake

{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}

Enter fullscreen mode Exit fullscreen mode

Server → client

{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2024-11-05","serverInfo":{"name":"hazeljs-mcp-starter-taskboard","version":"1.0.0"},"capabilities":{"tools":{}}}}

Enter fullscreen mode Exit fullscreen mode

Client → server: discover tools

{"jsonrpc":"2.0","id":2,"method":"tools/list"}

Enter fullscreen mode Exit fullscreen mode

Server → client (truncated)

{"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"add_task","description":"Create a new open task with the given title.","inputSchema":{"type":"object","properties":{"title":{"type":"string","description":"Short description of the work item"}},"required":["title"]}}, ]}}

Enter fullscreen mode Exit fullscreen mode

Client → server: call a tool

{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"add_task","arguments":{"title":"Buy milk"}}}

Enter fullscreen mode Exit fullscreen mode

Server → client

{"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"{\"id\":\"tsk_1\",\"title\":\"Buy milk\",\"status\":\"open\",\"createdAt\":\"2026-05-09T16:49:51.862Z\"}"}],"isError":false}}

Enter fullscreen mode Exit fullscreen mode

Heads up: MCP is JSON-RPC, not a CLI. Typing bare commands like list_tasks into the running server's stdin returns -32700 Parse error — that is the spec correctly rejecting non-JSON input, not a bug.

If you want a friendly REPL on top of these tools, build it as a separate script that consumes the registry directly. The MCP server itself must remain protocol-pure so real clients can talk to it.


8. Running the starter

Clone the hazel-js/hazeljs-mcp-starter repository and install:

git clone git@github.com:hazel-js/hazeljs-mcp-starter.git
cd hazeljs-mcp-starter
npm install
npm run build

Enter fullscreen mode Exit fullscreen mode

You should now have dist/main.js. To run it standalone (it will block on stdin, which is normal):

node dist/main.js

Enter fullscreen mode Exit fullscreen mode

To exercise the protocol without typing JSON by hand, paste these envelopes one per line into the running server's stdin and press Enter after each:

{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}
{"jsonrpc":"2.0","id":2,"method":"tools/list"}
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"add_task","arguments":{"title":"Buy milk"}}}
{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"list_tasks","arguments":{}}}
{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"board_stats","arguments":{}}}

Enter fullscreen mode Exit fullscreen mode

That's the fastest feedback loop for "did my change break the protocol?" — much faster than a full Cursor reload.

The repository's package.json pins published versions of the HazelJS packages:

"@hazeljs/agent": "0.7.9",
"@hazeljs/mcp": "0.7.9"

Enter fullscreen mode Exit fullscreen mode


9. Wiring Cursor

Add a server entry to .cursor/mcp.json at your project root, with an absolute path to the built dist/main.js. Relative paths sometimes work, but absolute is unambiguous across reloads:

{
  "mcpServers": {
    "hazeljs-taskboard": {
      "command": "node",
      "args": ["/ABSOLUTE/PATH/TO/hazeljs-mcp-starter/dist/main.js"]
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Reload the MCP servers (or restart Cursor). The four tools should appear in the tool list, and the model can call them in chat. A natural prompt to try:

"Add a task titled 'Write MCP blog' and another 'Ship starter repo', mark the first one done, then show me board stats."

If something goes wrong, Cursor surfaces the JSON-RPC error code in its MCP logs. -32601 (method not found) usually means the server crashed and a different process is responding; -32603 (internal error) means a tool threw — log the exception in the server to see the real cause.


10. Wiring Claude Desktop (macOS)

In ~/Library/Application Support/Claude/claude_desktop_config.json, add the same command / args pair pointing at your dist/main.js. Restart Claude Desktop. Tool discovery happens automatically on next chat.

The same dist/main.js works for both Cursor and Claude Desktop because MCP is a contract, not a vendor protocol. That's the whole point.


11. From in-memory to production

The starter's array store is a placeholder; here are the swap-ins you will actually want.

Persistence with Prisma

import { PrismaClient } from '@prisma/client';

export class TaskBoardMcpAgent {
  constructor(private prisma: PrismaClient) {}

  @Tool({ name: 'add_task', description: 'Create a new open task', parameters: [
    { name: 'title', type: 'string', description: 'Title', required: true },
  ]})
  async addTask(input: { title: string }) {
    return this.prisma.task.create({
      data: { title: input.title.trim(), status: 'open' },
    });
  }
}

Enter fullscreen mode Exit fullscreen mode

Construct the agent with a PrismaClient once in main.ts; every tools/call reuses the connection pool.

Distributed state with Redis

For multi-process deployments where any worker can serve any call (e.g. a managed agent platform spinning up several MCP children), back the store with Redis. @Tool() doesn't change. The methods just become thin wrappers over redis.hSet / hGetAll.

Calling existing HTTP APIs

The most common path: your tools wrap existing REST or gRPC endpoints. Pass an httpClient (axios, undici, fetch) into the constructor and translate domain calls inside each @Tool(). This is typically the first MCP server a team ships — it gives the model read/write access to systems that are already running, without touching the underlying services.

Schema-first validation with Zod

For anything beyond toy tools, declare a Zod schema instead of a parameters[] array:

import { z } from 'zod';

const AddTaskInput = z.object({
  title: z.string().min(1).max(280),
  priority: z.enum(['low', 'medium', 'high']).default('medium'),
});

@Tool({
  name: 'add_task',
  description: 'Create a new open task',
  schema: AddTaskInput,
})
async addTask(input: z.infer<typeof AddTaskInput>) { ... }

Enter fullscreen mode Exit fullscreen mode

@hazeljs/agent converts the Zod schema to JSON Schema for tools/list and (with guardrails enabled) validates inputs before your method runs. You get autocomplete inside the method body and reject malformed inputs at the boundary, not deep inside business logic.


12. Error handling without surprises

There are two failure modes worth thinking about:

Programmer errors (bugs) should throw. The transport will return a -32603 INTERNAL_ERROR envelope, the client logs it, and you see a stack trace in stderr. Do not catch and swallow these.

User-facing failures (validation, "not found", "already completed") should return a structured result instead of throwing. Example:

async completeTask(input: { task_id: string }) {
  const task = this.tasks.find((t) => t.id === input.task_id);
  if (!task) {
    return { ok: false, error: `No task with id: ${input.task_id}` };
  }
  task.status = 'done';
  return { ok: true, task };
}

Enter fullscreen mode Exit fullscreen mode

The model sees a normal JSON response and can recover gracefully (e.g. ask the user to confirm the ID). Reserve thrown exceptions for "this should never happen" cases.

For protocol-level errors (-32700, -32601, -32602) you don't write any code — the package generates the right envelope automatically.


13. Multi-agent registries

Real systems split tools across domains. You can register multiple agents into the same registry:

const registry = new ToolRegistry();
registry.registerAgentTools('support', new SupportAgent(deps));
registry.registerAgentTools('billing', new BillingAgent(deps));
registry.registerAgentTools('admin', new AdminAgent(deps));

const server = createMcpServer({ name: 'company-tools', version: '1.0.0', toolRegistry: registry });
server.listenStdio();

Enter fullscreen mode Exit fullscreen mode

Tool names must be globally unique at the MCP layer because the adapter keys by short name. Either pick distinct name values (e.g. support_lookup_customer vs billing_lookup_customer) or run separate processes per domain. The latter is often cleaner: it gives you per-domain logging, restart blast-radius, and access controls.


14. Security: what to check before shipping

MCP servers run as child processes of trusted clients, so the threat model is different from a public HTTP API — but it is not zero.

  • Treat tool inputs as untrusted. The model can be prompt-injected by an upstream document, page, or message, and forwarded inputs reflect that. Validate, escape, and bound everything you pass to your data layer (no raw SQL string-interpolation, no eval, no shell exec without an allowlist).
  • Don't log secrets. Tools often pass through API keys or PII. Strip secrets from winston / pino events. Hazel's logger supports redaction patterns; use them.
  • Bound destructive actions behind requiresApproval. @hazeljs/agent lets you mark tools that should pause for human approval. Use it for password resets, refunds, deletes — anything you would not want a model to do unattended.
  • Pin tool names. Renaming a tool can silently degrade an agent that learned to call it. If you must rename, alias the old name for a deprecation window.

15. Observability

Because the server is "just Node.js," any logger or metrics backend you already use works:

  • Logs: wrap the agent with a Proxy (or a @hazeljs/agent middleware) that logs tool_name, duration_ms, and is_error for every call. Five lines of code, enormous debugging value.
  • Metrics: export a counter mcp_tool_calls_total{tool, status} and a histogram mcp_tool_duration_seconds{tool}. Cursor will happily call your tools 10× per chat — you want a graph for that.
  • Tracing: start a span around each tools/call invocation and propagate it into downstream HTTP/db calls. OpenTelemetry's @opentelemetry/instrumentation-http covers most of it for free.

A nice property of MCP: because every interesting action is a tools/call, you get per-tool telemetry without any framework opinionation — just instrument the adapter once.


16. Comparing alternatives

Approach Pros Cons
Hand-written MCP server (no SDK) Full control, zero deps You re-implement JSON-RPC framing, error envelopes, JSON Schema mapping
Official MCP TypeScript SDK Officially maintained, full feature set (resources, prompts, sampling) Heavier, separate tool definition style; less idiomatic if you already use Hazel decorators
@hazeljs/mcp + @hazeljs/agent Single tool definition shared with your agent runtime, ~200-line transport, no deps Tool-only today (resources/prompts not yet covered)
Custom HTTP API consumed by an agent Familiar mental model, easy to test Every IDE / client needs a bespoke integration; not portable
OpenAI-only function calling First-class in OpenAI clients Single-vendor; requires your code to be the orchestrator instead of the IDE

For most teams already running TypeScript backends, @hazeljs/mcp hits the sweet spot: write your tools once with @Tool(), expose them to every MCP client today, and migrate to the official SDK later if you need resources/prompts/sampling.


17. Where to go next

  • Replace the in-memory store with your real data layer (Prisma, Drizzle, MongoDB, or an HTTP client over your existing services).
  • Add a domain-specific server for each subsystem (support, billing, infra) and register them under separate .cursor/mcp.json entries — one process per blast-radius.
  • Adopt Zod schemas with @Tool({ schema }) for validated inputs and inferred TypeScript types in the method body.
  • Wire approvals with requiresApproval: true on destructive tools and configure your client to gate them.
  • Layer observability (logs + metrics + traces) at the adapter level, not inside each tool.
  • Read the package source@hazeljs/mcp on GitHub is small enough to read in 15 minutes and understanding it makes debugging trivial.

The combination of @Tool() and @hazeljs/mcp keeps the server's surface area small: one decorator per method, one registry, one createMcpServer, one line to listen. Your domain logic stays domain logic, the protocol stays plumbing, and any MCP-aware client picks up your tools for free.


References