Build an MCP Server in TypeScript and Use It in Cursor: A Hands-On Guide
Step-by-step guide to building a Model Context Protocol (MCP) server in TypeScript: tools, resources, prompts, testing with MCP Inspector, and connecting it to Cursor — plus the GitHub and Playwright MCP servers.

The Model Context Protocol (MCP) is an open standard for connecting AI assistants to tools and data. Instead of every editor and chatbot inventing its own plugin format, you write one MCP server and it works in Cursor, Claude, VS Code and any other MCP client.
In this guide we'll build a small but real MCP server in TypeScript — repo-insights, which lets the AI in Cursor list a GitHub repository's open issues and read its README — then connect it to Cursor, test it, and add a couple of ready-made servers next to it.
Written against @modelcontextprotocol/sdk 1.32, zod 4 and TypeScript 7. The full server below compiles and runs as shown.
How MCP works in one minute
An MCP client (Cursor) starts or connects to an MCP server (your program). They talk JSON-RPC over a transport — usually stdio for local servers (the client launches your process and talks to it over stdin/stdout) or HTTP for remote ones.
A server can offer three kinds of things:
- Tools — functions the model can call, like
list_open_issues. This is what you'll use 90% of the time. - Resources — read-only data the client can load into context, addressed by a URI like
github://vercel/next.js/readme. - Prompts — reusable prompt templates that show up as commands in the client.
Step 1: Set up the project
You need Node.js 18 or newer.
1mkdir repo-insights && cd repo-insights
2npm init -y
3npm install @modelcontextprotocol/sdk zod
4npm install -D typescript @types/node
5npm pkg set type=moduletype: module matters because the server uses top-level await, which only works in an ES module.
Create a tsconfig.json by hand. Recent versions of tsc --init set "types": [], which hides Node's process and Buffer globals:
1{
2 "compilerOptions": {
3 "target": "es2022",
4 "module": "nodenext",
5 "moduleResolution": "nodenext",
6 "types": ["node"],
7 "outDir": "build",
8 "rootDir": "src",
9 "strict": true,
10 "skipLibCheck": true
11 },
12 "include": ["src"]
13}Step 2: Create the server and a GitHub helper
1// src/index.ts
2import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js'
3import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
4import { z } from 'zod'
5
6const API = 'https://api.github.com'
7const headers: Record<string, string> = {
8 Accept: 'application/vnd.github+json',
9 'User-Agent': 'repo-insights-mcp',
10 ...(process.env.GITHUB_TOKEN ? { Authorization: `Bearer ${process.env.GITHUB_TOKEN}` } : {}),
11}
12
13async function gh<T>(path: string): Promise<T> {
14 const res = await fetch(`${API}${path}`, { headers })
15 if (!res.ok) throw new Error(`GitHub ${res.status}: ${await res.text()}`)
16 return res.json() as Promise<T>
17}
18
19const server = new McpServer({ name: 'repo-insights', version: '1.0.0' })The GITHUB_TOKEN is optional; without it you get GitHub's low anonymous rate limit.
Step 3: Add a tool
Tools are registered with a name, a description, and an input schema written in zod. The SDK turns the schema into JSON Schema for the model and validates every call before your handler runs.
1server.registerTool(
2 'list_open_issues',
3 {
4 title: 'List open issues',
5 description: 'List open issues in a GitHub repository, newest first. Use for triage or summaries.',
6 inputSchema: {
7 owner: z.string().describe('Repository owner, e.g. "vercel"'),
8 repo: z.string().describe('Repository name, e.g. "next.js"'),
9 label: z.string().optional().describe('Only issues with this label'),
10 limit: z.number().int().min(1).max(50).default(10),
11 },
12 },
13 async ({ owner, repo, label, limit }) => {
14 const params = new URLSearchParams({ state: 'open', per_page: String(limit) })
15 if (label) params.set('labels', label)
16 try {
17 const issues = await gh<Array<{ number: number; title: string; pull_request?: unknown; html_url: string }>>(
18 `/repos/${owner}/${repo}/issues?${params}`,
19 )
20 const lines = issues
21 .filter((i) => !i.pull_request) // GitHub's issues API also returns PRs
22 .map((i) => `#${i.number} ${i.title} — ${i.html_url}`)
23 return { content: [{ type: 'text', text: lines.join('\n') || 'No open issues.' }] }
24 } catch (err) {
25 return { content: [{ type: 'text', text: `Failed: ${(err as Error).message}` }], isError: true }
26 }
27 },
28)Three things make a tool work well with a model:
- The description is the documentation. The model decides when to call your tool based on it. Say what it does and when to use it.
.describe()every parameter with an example. It noticeably reduces malformed calls.- Return errors as results, with
isError: true, instead of throwing. The model sees the message and can correct itself — for example, by fixing a misspelled repo name.
Step 4: Add a resource and a prompt
A resource template exposes data at a URI pattern. Here, the client can load any repository's README into context:
1server.registerResource(
2 'readme',
3 new ResourceTemplate('github://{owner}/{repo}/readme', { list: undefined }),
4 { title: 'Repository README', mimeType: 'text/markdown' },
5 async (uri, { owner, repo }) => {
6 const file = await gh<{ content: string }>(`/repos/${owner}/${repo}/readme`)
7 return { contents: [{ uri: uri.href, text: Buffer.from(file.content, 'base64').toString('utf8') }] }
8 },
9)And a prompt packages a workflow users can trigger by name:
1server.registerPrompt(
2 'triage',
3 {
4 title: 'Triage a repository',
5 description: 'Summarise open issues and suggest priorities',
6 argsSchema: { owner: z.string(), repo: z.string() },
7 },
8 ({ owner, repo }) => ({
9 messages: [
10 {
11 role: 'user',
12 content: {
13 type: 'text',
14 text: `Use list_open_issues for ${owner}/${repo}, group the issues by theme, and suggest the top 3 to fix first.`,
15 },
16 },
17 ],
18 }),
19)Step 5: Connect the transport
1const transport = new StdioServerTransport()
2await server.connect(transport)
3console.error('repo-insights MCP server running on stdio')Note console.error, not console.log. With the stdio transport, stdout is the protocol channel. A stray console.log corrupts the JSON-RPC stream and the client disconnects with a confusing error. Log to stderr, always.
Build it:
1npx tscStep 6: Test with MCP Inspector before touching Cursor
The MCP Inspector is a small web UI that connects to your server so you can call tools by hand:
1npx @modelcontextprotocol/inspector node build/index.jsOpen the URL it prints, click Connect, then List Tools, and run list_open_issues with a public repo. If it works here, any problem in Cursor is configuration, not code.
Step 7: Add it to Cursor
Cursor reads MCP servers from .cursor/mcp.json in your project (or ~/.cursor/mcp.json for every project):
1{
2 "mcpServers": {
3 "repo-insights": {
4 "command": "node",
5 "args": ["/absolute/path/to/repo-insights/build/index.js"],
6 "env": { "GITHUB_TOKEN": "ghp_your_token_here" }
7 }
8 }
9}Use an absolute path — Cursor doesn't launch the server from your project folder. Then open Cursor Settings → MCP: the server should show a green dot and list its tools. In Agent chat, ask "What are the open bug issues in vercel/next.js?" and Cursor will ask permission to call list_open_issues.
Keep real tokens out of a committed .cursor/mcp.json. Use the global file for secrets, or add the project file to .gitignore.
Step 8: Combine it with ready-made servers
You don't have to write everything yourself. Two servers I pair with custom ones:
- GitHub's official MCP server — full repository, issue and pull request access, maintained by GitHub. It runs as a hosted remote server or locally via Docker. (The old
@modelcontextprotocol/server-githubnpm package is archived; don't use it.) - Playwright MCP (
@playwright/mcp) — browser automation: navigate, click, fill forms and read pages through the accessibility tree. It has replaced the archived Puppeteer server for most use cases.
1{
2 "mcpServers": {
3 "playwright": { "command": "npx", "args": ["@playwright/mcp@latest"] }
4 }
5}With repo-insights and Playwright together, you can ask Cursor to "take the top bug from vercel/next.js, open the reproduction link, and tell me if it still happens" — and watch it chain the tools.
Troubleshooting
- Server shows red / "client closed" — run the exact
commandandargsin a terminal. Usually it's a wrong path or a missing build. - Tools don't appear — restart the server from Cursor's MCP settings after every rebuild.
- Garbled responses — something is writing to stdout. Search for
console.log. - Model never calls the tool — improve the description and say when to use it. Too many enabled tools also dilutes the model's choices, so turn off servers you're not using.
Security notes
An MCP server runs with your permissions. Treat it like any dependency you execute: read third-party servers before installing them, give tokens the smallest scope that works (a read-only fine-grained GitHub token is enough here), and keep tools that write or delete behind explicit confirmation.
Where to go next
- Add a second transport — the SDK's Streamable HTTP transport lets you host the same server remotely for your team.
- Read Vectorless RAG: Why It Exists and What's Wrong with Vector Embeddings — retrieval tools are one of the most useful things to expose over MCP.
- If you're building agents in JavaScript, see LangChain for JS Developers.
Share this article
Found it helpful? Share it with your network.
Keep reading

Building a Python Script to Convert Videos to Instagram Reels Format
Building a Python Script to Convert Videos to the Instagram Reels Format | TaylorAmitVerma Blogs