Rajesh DhimanRajesh Dhiman
Free AuditServicesCase StudiesProjectsBooksBlogResourcesAboutContact
Book a CallRD
  1. Home
  2. Blog
  3. How I Turned a REST API into an MCP Server

How I Turned a REST API into an MCP Server

RDRajesh Dhiman
May 19, 2025
5 min read
AI Agents & MCP
Production AI & LLMs
MCP
Zod
OpenAPI
LLM
TypeScript
AI Tools
Developer Tools
Agent Ready

πŸ” Introduction: Turning a Fast Food Joint into Fine Dining

Let’s say you walk into a fast food restaurant. You shout, β€œOne burger!” and they toss it to you in under 30 seconds. Quick, dirty, and done. That’s your typical REST API: fast, unstructured, and a little unpredictable.

But what if you wanted to open a high-end place β€” where every dish has a printed menu, the ingredients are verified, and the chef follows a consistent recipe? That’s what Model Context Protocol (MCP) servers are like. They don’t just serve data; they serve it with structure, clarity, and a smile.

In this post, I’ll show you exactly how I wrapped the public Hacker News API in an MCP β€” turning a chaotic data stream into a clean, LLM-friendly microservice.


🧠 Wait... What’s an MCP Again?

Let me break it down:

MCP stands for Model Context Protocol. It’s an open standard for connecting AI applications to external tools and data, where every tool:

  • Has a clear input contract, described with JSON Schema
  • Is exposed by an MCP server that clients can discover
  • Can be called by LLMs through any MCP client
  • Plays nicely in a function-calling world (like OpenAI or Claude)

In simple terms: it's like giving every tool its own resume. It knows who it is, what it accepts, and what it gives back.

The wrapper in this post applies that contract-first idea to plain REST endpoints, using Zod contracts and OpenAPI docs. It doesn't speak MCP's JSON-RPC protocol, so exposing it to MCP clients takes one more step: registering the endpoints as tools with an MCP SDK.


πŸ”₯ Why Wrap an Existing API?

I wanted to showcase how powerful MCPs are by not building everything from scratch. Instead, I took the Hacker News API β€” a basic REST interface with zero documentation, no validation, and no structure β€” and made it:

  • 🌱 Type-safe with Zod
  • πŸ€– Callable by LLM agents
  • πŸ“œ OpenAPI-exportable via zod-openapi
  • 🌍 Deployable & reusable

You get all the benefits of modern, clean backend architecture β€” without rebuilding the wheel.


🚧 Step 1: Picking the API

I went with Hacker News API. Why?

  • It’s public and requires no authentication
  • It returns JSON (yay!)
  • It’s a little raw β€” making it perfect for a glow-up

Hacker News gives you endpoints like:

  • /topstories.json β†’ returns an array of story IDs
  • /item/{id}.json β†’ returns the details for a story or comment

But there’s no validation. No input schema. No docs. Just vibes.


🧱 Step 2: MCP Project Structure

I set up the project with this simple folder structure:

src/
β”œβ”€β”€ contracts/                // Zod + OpenAPI metadata
β”œβ”€β”€ resolvers/                // Business logic
β”œβ”€β”€ handlers/                 // Express routes
β”œβ”€β”€ utils/                    // Hacker News client
β”œβ”€β”€ docs/openapi.ts           // OpenAPI spec generator (zod-openapi)
β”œβ”€β”€ setup/zod-openapi-init.ts // Shared zod setup with OpenAPI support
└── server.ts                 // Main entry point 

Think of it like building with LEGO blocks β€” every piece does one thing, and snaps into place without duct tape.


πŸ§ͺ Step 3: Creating the First Contract

Let’s start with the endpoint to list top stories.

βœ… Zod Contract

export const listTopStoriesOutput = z.array(z.number()).openapi({
  description: "Array of Hacker News story IDs",
}); 

It’s like saying: β€œHey, this endpoint gives back an array of numbers. No more, no less.”


βš™οΈ Step 4: Writing the Resolver

The resolver is the actual brain. It connects to Hacker News, fetches the data, and validates it.

import { fetchTopStoryIds } from "../utils/hnClient";
import { listTopStoriesOutput } from "../contracts/listTopStories.contract";

export const listTopStoriesHandler = async (req, res) => {
  try {
    const storyIds = await fetchTopStoryIds();
    res.json(listTopStoriesOutput.parse(storyIds));
  } catch (e) {
    res.status(500).json({ error: "Something went wrong!" });
  }
}; 

πŸ“– Step 5: Adding the getStory Endpoint

This one lets you fetch details about any story by ID.

βœ… Input Contract

export const getStoryInput = z
  .object({
    id: z
      .string()
      .regex(/^[0-9]+$/)
      .openapi({ description: "Story ID" }),
  })
  .openapi({ title: "GetStoryInput" }); 

βœ… Output Contract

export const getStoryOutput = z
  .object({
    id: z.number().openapi({ description: "ID of the story" }),
    title: z.string().openapi({ description: "Title of the story" }),
    by: z.string().openapi({ description: "Author" }),
    score: z.number().openapi({ description: "Score or points of the story" }),
    url: z.string().optional().openapi({ description: "URL (if any)" }),
    time: z.number().openapi({ description: "Unix timestamp" }),
    type: z.string().openapi({ description: "Item type (story/comment)" }),
  })
  .openapi({ title: "GetStoryOutput" }); 

πŸš€ Step 6: Hosting + OpenAPI + LLM Ready

After writing the resolvers, I hosted the whole thing here:

πŸ”— https://mcp-news-server.onrender.com

Test it:

  • /api/listTopStories
  • /api/getStory/8863
  • /openapi.json

And yes, it works with LangChain, Claude, OpenAI, or any custom LLM runner!


🎁 What You Can Do Next

  • Wrap any REST API you love in an MCP
  • Add contracts, deploy, and share with LLMs
  • Use zod-openapi to create swagger-compatible specs
  • Register it in an agent-aware toolchain or build your own GPT plugin

πŸ’¬ TL;DR

Contract-first design, the idea behind MCP tools, gives your API structure and meaning. By wrapping a basic REST API like Hacker News with Zod contracts and generating OpenAPI with zod-openapi, you can:

  • Build more robust backend tools
  • Make them compatible with LLMs
  • Reduce guesswork and increase composability

Let’s stop building brittle REST services β€” and start building smart, structured, machine-readable APIs.

πŸ’‘ Try it yourself β€” and let me know what you wrap next!

Free field guide

Ship AI features that survive real traffic

Start from the failure modes, choose the smallest architecture that holds up, and instrument the path before you scale it.

No spam, unsubscribe anytime. You will also get instant access on the next screen.

Share this article

TwitterLinkedInFacebook
Buy Me a Coffee
Support my work

If you found this article helpful, consider buying me a coffee to support more content like this.

Buy a Coffee
RD

Written by

Rajesh Dhiman

Founder of Eunix Tech Β· Author Β· AI Systems Engineer

I've been building software for over a decade and I'm the founder of Eunix Tech, a software consultancy. I've written two books, the Vibe Coding Survival Guide and the Frontend Interview Guide, plus a set of practical engineering checklists. I spent 4 years at Alloy Automation building integrations for companies like Amazon and Best Buy, and I'm a top-rated mentor on Codementor (5.0 from 26 reviews). Today I rescue failing AI projects, audit AI-generated and no-code apps, and build production-grade automation that delivers measurable ROI.

AboutBooksEunix TechLinkedInGitHubXCodementor

Related Articles

AI Agent Skills vs Tools: The Distinction Every Developer Gets Wrong
AI Agent Skills vs Tools: The Distinction Every Developer Gets Wrong
5/4/2026

Most developers build agents with tools. That's not enough. Here's the architectural difference between agent tools and agent skills β€” and why getting this wrong burns tokens, degrades accuracy, and makes your agents brittle in production.

Why You Keep Hitting Claude's Usage Limits (And 5 Token Tricks That Actually Fix It)
Why You Keep Hitting Claude's Usage Limits (And 5 Token Tricks That Actually Fix It)
5/4/2026

Claude doesn't count messages like ChatGPT β€” it counts tokens, and one conversation can burn 10x more than another. Here are 5 tricks that cut your token usage by 80% or more.

A2A vs MCP: Agent Chatter vs Contract Clarity
A2A vs MCP: Agent Chatter vs Contract Clarity
5/22/2025

Explore the key differences between Agent-to-Agent (A2A) communication and the Model Context Protocol (MCP) β€” and why you need both to build powerful AI systems.

On this page

  • πŸ” Introduction: Turning a Fast Food Joint into Fine Dining
  • 🧠 Wait... What’s an MCP Again?
  • πŸ”₯ Why Wrap an Existing API?
  • 🚧 Step 1: Picking the API
  • 🧱 Step 2: MCP Project Structure
  • πŸ§ͺ Step 3: Creating the First Contract
  • βœ… Zod Contract
  • βš™οΈ Step 4: Writing the Resolver
  • πŸ“– Step 5: Adding the getStory Endpoint
  • βœ… Input Contract
  • βœ… Output Contract
  • πŸš€ Step 6: Hosting + OpenAPI + LLM Ready
  • 🎁 What You Can Do Next
  • πŸ’¬ TL;DR
Free field guide

Ship AI features that survive real traffic

Start from the failure modes, choose the smallest architecture that holds up, and instrument the path before you scale it.

No spam, unsubscribe anytime. You will also get instant access on the next screen.

App failing in production or automation that keeps breaking? Book a technical diagnostic β†’

Rajesh DhimanRajesh Dhiman

Β© 2026 Eunix Tech

Tickoff: one link for client files, answers and payment

Free AuditServicesCase StudiesProjectsBooksBlogResourcesMy StackAboutContact