Building Your Own MCP Server with TypeScript and Bun
Hello, this is Lovefield.
When integrating AI coding agents or desktop AI assistants into daily engineering workflows, a familiar bottleneck quickly emerges: the model writes great code, yet it cannot directly access your team's internal docs, local databases, or custom scripts—forcing you to copy and paste context manually.
MCP (Model Context Protocol) solves this as an open standard. Much like USB-C unified hardware peripherals under a single connector, MCP standardizes how AI applications (Hosts) communicate with external data sources and tools (Servers).
In this guide, we will move beyond consuming pre-built integrations and walk through building your own lightweight MCP server using TypeScript and Bun.
Understanding the MCP Architecture at a Glance
Before writing code, it helps to map out the three core components of MCP:
MCP Host: The AI application you interact with directly (e.g., Claude Desktop, Cursor, or an IDE agent).
MCP Client: Lives inside the Host, maintaining a 1:1 connection with each MCP server and exchanging JSON-RPC messages.
MCP Server: A lightweight program that bridges the AI with local files, databases, or APIs by exposing structured capabilities.
An MCP server can expose Tools (executable functions), Resources (read-only data/files), and Prompts (reusable prompt templates). In practice, Tools are almost always the best starting point for automating real workflows.

Initializing an MCP Project with Bun
Because local MCP servers are spawned on demand as subprocesses by AI clients, Bun is an ideal runtime—executing TypeScript files natively with near-zero startup latency and no separate build step.
Create a new project directory and install the official MCP SDK alongside zod for schema validation:
Shell
1
2
3
mkdir my-mcp-server && cd my-mcp-server
bun init -y
bun add @modelcontextprotocol/sdk zodImplementing a Practical MCP Server and Tool
Let's build a focused MCP server (src/index.ts) that searches local Markdown documentation by keyword and returns relevant snippets. Using Bun's native Bun.Glob and Bun.file APIs keeps the implementation fast and dependency-free.
TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// src/index.ts
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';
import { join } from 'node:path';
// 1. Initialize the MCP server instance
const server = new McpServer({
name: 'dico-docs-helper',
version: '1.0.0',
});
const DOCS_DIR = Bun.env.DOCS_DIR ?? './docs';
// 2. Register a Tool that the AI agent can invoke
server.tool(
'search_local_docs',
'Search local Markdown documentation files containing a specific keyword.',
{
keyword: z.string().min(1).describe('The search keyword to look for'),
limit: z.number().int().min(1).max(20).default(5).describe('Maximum number of results to return'),
},
async ({ keyword, limit }) => {
const glob = new Bun.Glob('**/*.md');
const matches: { file: string; snippet: string }[] = [];
for await (const relativePath of glob.scan(DOCS_DIR)) {
const fullPath = join(DOCS_DIR, relativePath);
const content = await Bun.file(fullPath).text();
if (content.toLowerCase().includes(keyword.toLowerCase())) {
const index = content.toLowerCase().indexOf(keyword.toLowerCase());
const snippet = content.slice(Math.max(0, index - 60), index + 120).replace(/\n/g, ' ');
matches.push({ file: relativePath, snippet });
}
if (matches.length >= limit) break;
}
if (matches.length === 0) {
return {
content: [{ type: 'text', text: `No documents matched '${keyword}'.` }],
};
}
const formatted = matches
.map((item) => `- **${item.file}**: ...${item.snippet}...`)
.join('\n');
return {
content: [{ type: 'text', text: formatted }],
};
},
);
// 3. Connect via Stdio transport and start the server
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error('dico-docs-helper MCP server running on Stdio');
}
main().catch((error) => {
console.error('Failed to start MCP server:', error);
process.exit(1);
});Pay close attention to the tool description and each Zod field's .describe() string. The AI model relies directly on these descriptions to decide when to call your tool and how to populate its arguments—clear metadata directly translates into higher agent accuracy.
Connecting to Local AI Clients and Debugging Tips
To register your server in an MCP Host like Claude Desktop or Cursor, point the configuration to bun run with the absolute path to your entry file:
JSON
1
2
3
4
5
6
7
8
9
10
11
{
"mcpServers": {
"dico-docs-helper": {
"command": "bun",
"args": ["run", "/Users/yourname/projects/my-mcp-server/src/index.ts"],
"env": {
"DOCS_DIR": "/Users/yourname/projects/my-blog/posts"
}
}
}
}One critical gotcha when building Stdio-based MCP servers is never using console.log().
Because the Stdio transport uses stdout exclusively for JSON-RPC protocol messages, even a single stray console.log() statement corrupts the stream and immediately breaks the client connection. Always write diagnostic logs to console.error() (stderr), as shown in the example above.
Summary
MCP provides the most practical bridge for turning your existing developer environment and internal APIs into first-class capabilities for AI agents—without training custom models.
Pairing TypeScript's type safety with Bun's instant execution lets you build reliable, custom tools in roughly 50 lines of code. Pick one repetitive lookup or internal API you check every day and wrap it as your first MCP Tool.
This article was generated by AI.

Lovefield
Web Front-End developer
하고싶은게 많고, 나만의 서비스를 만들고 싶은 변태스러운 개발자입니다.

Preventing Memory Leaks with Vue 3.5 useTemplateRef and onWatcherCleanup
Learn how to improve DOM reference type safety and eliminate async race conditions and event listener memory leaks in Vue 3.5 using useTemplateRef() and onWatcherCleanup().
Vue