Context & Why You Need a Custom MCP Server
Connecting an AI agent to internal APIs, Postgres databases, or local runbooks usually turns into a pile of brittle glue code. OpenAI expects one function-calling schema, Anthropic expects another, and IDE extensions expect a third. Supporting just 4 internal services across 3 clients quickly leaves you maintaining 12 nearly identical wrappers.
The Model Context Protocol (MCP) eliminates that duplication. It acts as a standard JSON-RPC 2.0 bridge between AI hosts—such as Claude Desktop, Cursor, or custom agent runtimes—and your backend systems. Build one MCP server, and every compatible client can discover and use it immediately.
Moving AI prototypes into production requires predictable interfaces, not ad-hoc scripts. Every MCP server revolves around two core primitives:
- Tools: Executable functions the model can call, such as checking a
/healthendpoint, opening a Jira ticket, or querying a read-replica table. - Resources: Read-only context the model can pull on demand, like deployment runbooks, service catalogs, or the last 100 lines of an error log.
Skip plain JavaScript here and start with TypeScript. Pairing TypeScript with Zod gives you static type checking at compile time and strict schema validation at runtime. When an LLM hallucinates a string instead of a port number, Zod catches it before it hits your business logic.
Installation: Setting Up Your TypeScript MCP Project
Start with a clean Node.js project configured for ECMAScript Modules (ESM). The official TypeScript MCP SDK ships as ESM, and fighting CommonJS interoperability issues is an easy way to burn an afternoon.
Create a project folder and install the SDK, Zod, and TypeScript:
mkdir my-mcp-server && cd my-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node
Node.js 18 or higher is required for native fetch and AbortSignal.timeout support. Set "type": "module" in package.json and configure a build script that makes your compiled entry point executable:
{
"name": "my-mcp-server",
"version": "1.0.0",
"type": "module",
"bin": {
"my-mcp-server": "./build/index.js"
},
"scripts": {
"build": "tsc && chmod 755 build/index.js"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.0.0",
"zod": "^3.23.0"
},
"devDependencies": {
"@types/node": "^22.0.0",
"typescript": "^5.5.0"
}
}
Module resolution matters next. In tsconfig.json, set both module and moduleResolution to Node16 (or NodeNext) so TypeScript resolves SDK subpath exports like /server/mcp.js cleanly:
{
"compilerOptions": {
"target": "ES2022",
"module": "Node16",
"moduleResolution": "Node16",
"outDir": "./build",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"]
}
Configuration: Implementing Custom Tools, Resources, and Client Wiring
Scaffold src/index.ts once your build config is ready. Three practical habits will save you hours of debugging as you write handlers.
Tip 1: Never Write to stdout on a stdio Server
Local MCP servers talk to AI clients over standard input and output (stdio). That pipe belongs exclusively to JSON-RPC frames. Drop a single console.log("Server started") in your startup path, and the client’s JSON parser will choke on it immediately. Route all diagnostic logs to console.error() instead, since host apps capture stderr separately.
Tip 2: Write Descriptive Tool Schemas and Graceful Error Responses
Models decide when and how to invoke a tool using only its name, description, and parameter docs. A vague description like "Check service" invites guessed URLs and missing parameters. Equally important: catch failures inside your callback and return isError: true rather than throwing unhandled exceptions. That lets the agent read the failure—such as an HTTP 503 or timeout—and adjust its next step.
Below is a working src/index.ts with one custom Tool (checking an endpoint’s status and latency) and one custom Resource (serving a deployment runbook):
#!/usr/bin/env node
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new McpServer({
name: "ops-assistant-server",
version: "1.0.0",
});
// 1. Register a Custom Tool
server.tool(
"check_service_health",
"Checks the HTTP status and response latency of an internal service URL.",
{
url: z.string().url().describe("Full HTTPS URL of the health endpoint to check"),
timeoutMs: z
.number()
.int()
.min(500)
.max(10000)
.default(3000)
.describe("Request timeout in milliseconds (500 to 10000)"),
},
async ({ url, timeoutMs }) => {
const start = Date.now();
try {
const response = await fetch(url, {
signal: AbortSignal.timeout(timeoutMs),
});
const duration = Date.now() - start;
return {
content: [
{
type: "text",
text: JSON.stringify(
{
url,
status: response.status,
ok: response.ok,
latencyMs: duration,
},
null,
2
),
},
],
};
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return {
isError: true,
content: [
{
type: "text",
text: `Health check failed for ${url}: ${message}`,
},
],
};
}
}
);
// 2. Register a Custom Resource
server.resource(
"deployment-runbook",
"runbook://ops/deployment",
async (uri) => {
const markdown = [
"# Production Deployment Runbook",
"1. Verify staging health checks return HTTP 200.",
"2. Confirm database migrations are backward-compatible.",
"3. Roll out to canary instances and monitor error rates for 10 minutes.",
].join("\n");
return {
contents: [
{
uri: uri.href,
mimeType: "text/markdown",
text: markdown,
},
],
};
}
);
async function main(): Promise<void> {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("ops-assistant-server is running on stdio");
}
main().catch((err) => {
console.error("Fatal error starting MCP server:", err);
process.exit(1);
});
Compile the TypeScript code before registering it with a client:
npm run build
Tip 3: Use Absolute Paths in Client Configuration
Desktop AI apps rarely inherit your interactive shell’s working directory or PATH. When editing Claude Desktop’s claude_desktop_config.json or Cursor’s MCP settings, point directly to the compiled build/index.js using an absolute path:
{
"mcpServers": {
"ops-assistant": {
"command": "node",
"args": ["/absolute/path/to/my-mcp-server/build/index.js"],
"env": {
"NODE_ENV": "production"
}
}
}
}
Keep API tokens and database credentials out of your TypeScript source. Inject them through the env block instead.
Verification & Monitoring: Testing and Debugging Your MCP Server
Resist the urge to test a brand-new server by chatting with an LLM right away. When something fails in chat, you cannot easily tell whether the bug lives in your TypeScript handler, the client config, or the model’s tool selection.
Inspect Tools and Resources Directly with the MCP Inspector
Use the official MCP Inspector to test your server deterministically in a local browser UI. Run it right after your build finishes:
npx @modelcontextprotocol/inspector node build/index.js
Run through three quick checks inside the Inspector:
- Tool discovery: Verify
check_service_healthlists bothurlandtimeoutMs(defaulting to3000) with their exact Zod constraints. - Error handling: Pass a dead local URL like
https://localhost:59999/healthand confirm the response setsisError: truewithout crashing the server. - Resource reads: Open
runbook://ops/deploymentand check that thetext/markdownpayload renders cleanly.
Monitor stderr Logs and Process Lifecycle
Once your server is wired to a live client, watch the host’s MCP logs to catch startup errors or slow calls early. On macOS with Claude Desktop, stream those logs in a terminal:
tail -f ~/Library/Logs/Claude/mcp*.log
On Linux servers or inside container runners, forward stderr to your structured log collector. Combine strict Zod input boundaries with explicit timeouts like AbortSignal.timeout(3000) so a hanging downstream API never stalls an entire agent turn.

