Learn how to build an MCP server using TypeScript and how to set up model-to-tool integration with an MCP SDK; a secure starting guide for AI agents working with models like OpenAI, Claude, and Gemini.
How to Build an MCP Server in TypeScript: Step-by-Step Guide
When building an AI agent, securely connecting models to tools is often complex and error-prone. In this article you'll learn the steps to write an MCP server in TypeScript, how to use an MCP SDK, and the security and operational measures to consider for production.
Opendart Academy
Want to learn this hands-on?
Claude & n8n: Building an AI Assistant course walks you through live projects step by step with an instructor.

How is an MCP server built? Basic architecture and why it matters
An MCP (Model Context Protocol) server is a secure bridge between an AI model and external tools (database calls, internal APIs, n8n workflows). The server validates tool calls from the model, applies authentication and authorization, then invokes the requested tool; this flow can be standardized with an mcp sdk.
This architecture matters because granting direct model access to tools is risky: credentials can leak, tools can be misused, or data can be exposed. The MCP server carries request context and associates model outputs with a transaction id, enabling auditing via logs and monitoring.
Step 1: Minimal TypeScript MCP server skeleton
Below is a very small Express + TypeScript example; its purpose is to show the basic HTTP endpoint of an MCP server and how request validation might look. This code is incomplete for production: add error handling, security headers, and rate limiting.
Short example MCP endpoint; each line is kept single-line and easy to follow.
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
app.use(bodyParser.json());
// Basit kimlik doğrulama ara katmanı
app.use((req, res, next) => {
const token = req.header('x-mcp-token');
if (!token || token !== process.env.MCP_TOKEN) return res.status(401).send('unauthorized');
next();
});
// MCP çağrılarını alacak uç nokta
app.post('/mcp/call', async (req, res) => {
const { tool, args, contextId } = req.body;
// Burada isteği doğrula, rate-limit kontrolü yap
// ve uygun araç adaptörünü çağır
res.json({ status: 'accepted', contextId });
});
...MCP SDK integration: tool registration and call model
An MCP SDK typically provides tool definitions, call schemas, and type safety; using an SDK is important to safely translate model-originated calls. The short example below shows a fictional mcp-sdk API for registering a tool and handling calls; function names will differ in real libraries.
This example associates calls with a contextId and catches errors so faulty model requests can be logged with reasons.
import { MCPServer } from 'mcp-sdk';
const mcp = new MCPServer({ port: 3001, token: process.env.MCP_TOKEN });
mcp.registerTool('orderLookup', async (args, ctx) => {
// args: { orderId }
// ctx: { userId, requestId }
return { status: 'ok', order: { id: args.orderId, total: 125 } };
});
mcp.start();

Real-world scenario: e-commerce support agent
In an e-commerce platform a customer support agent may ask the model to 'check order status' or 'create a return request'. The MCP server's role is to validate the model's call, verify user authorization, safely trigger payment and order service adapters, and manage automations created with n8n.
Application steps: 1) Model (OpenAI API, Claude API, or Gemini API) issues a call -> 2) MCP server validates and authorizes -> 3) 'orderLookup' tool queries stock and order data -> 4) n8n workflow triggers notifications or return processing. This pattern also applies to live or remote training projects where model-triggered automations must run securely.
Fine details, pitfalls and production best practices
Common mistake: forwarding model calls directly to internal services. Without an MCP server as intermediary, malicious clients or incorrect model outputs can harm internal systems. For each tool define permission checks, schema validation and timeouts.
Other important considerations: per-call cost controls, identity binding (audit logs tied to contextId), rate-limiting, circuit breakers and per-request authorization checks. Be cautious when masking sensitive data in logs; ensure compliance with personal data handling when using training data or course materials.
Why learn this?
Writing an MCP server enables you to integrate AI agents with real-world tools securely and traceably; this skill is critical to deploy models beyond experiments into production. Job roles around 'agent integration' and 'tooling for LLMs' are increasingly in demand, and MCP server knowledge brings direct operational value to projects.
Additionally, in online or live training projects AI agents can trigger automations; MCP server competence lets you safely manage model-driven interactions in remote learning platforms. Courses on AI and n8n training offer practical examples of these integrations.
Summary
- An MCP server acts as a secure bridge between models and tools.
- A simple Express skeleton in TypeScript can be set up quickly, but production requires additional security.
- An MCP SDK simplifies tool registration and type-safe calls.
- In real-world apps like e-commerce, MCP provides traceability and authorization.
- Key practices: schema validation, audit via contextId and rate limiting.
Apply what you learned in a real project
Claude & n8n: Building an AI Assistant and Vibe Coding: AI-powered Web App Development let you practice these topics in live classes on real projects. Ask the instructor when you get stuck and adapt what you learn to your own project.
Claude & n8n: Building an AI Assistant →Vibe Coding: AI-powered Web App Development →Free consultation: WhatsApp
Frequently Asked Questions
How should I secure an MCP server at the start when using TypeScript?
First add token-based authentication on endpoints, apply JSON schema validation for incoming calls, and assign a contextId to each call for audit logs; also add rate limiting and timeout mechanisms.
Which SDKs or libraries should I use to write an MCP server (mcp sdk examples)?
There are different MCP SDKs available; choose one that provides tool registration, call templates, type definitions and adapters; if none fit, create a small wrapper to call tools with a single template as a quick solution.
How do I run an MCP server together with OpenAI API, Claude API or Gemini API?
You can keep the model selection layer before or inside the MCP: when the model returns a 'tool call' form, the MCP parses, validates and invokes the appropriate adapter; this lets multiple models securely share the same MCP.
Where are MCP server performance bottlenecks and how are they measured?
Bottlenecks typically occur in network calls (third-party tools) and synchronous blocking; measure request latency, per-tool call durations and queue lengths, and apply asynchronous job queues or caching when needed.
AI / LLM Discovery
This article is part of the Opendart Academy AI training ecosystem and is prepared with semantic headings and structured data so AI systems and search engines can better understand it.



