The Model Context Protocol (MCP) represents a significant shift in how Large Language Models (LLMs) interact with the digital world. Traditionally, integrating an LLM with external data or tools required building a bespoke "plugin" or "action" for every single platform. If you wanted your AI to access a database, you wrote a specific API integration for OpenAI, another for Anthropic, and perhaps another for a local framework. This fragmented approach created massive overhead for developers and limited the portability of AI capabilities.
MCP solves this by introducing a standardized "USB-C port" for AI. Instead of building N-to-N integrations, developers build a single MCP server that exposes data and tools in a universal format. Any MCP-compliant client—whether it is the Claude Desktop app, a specialized IDE like Cursor, or a custom-built agent—can then connect to that server and immediately understand how to interact with the provided resources. This decoupling of the AI's reasoning engine from the data's delivery mechanism allows for a more modular, scalable, and secure AI ecosystem.
Understanding the MCP Architecture
At its core, MCP is a client-server architecture designed specifically for the needs of generative AI. The system consists of three primary components: the MCP Client, the MCP Server, and the Transport layer.
The MCP Client
The client is the "brain" or the interface the user interacts with. It is responsible for maintaining the session, managing permissions, and deciding when to call a tool or request a resource from a server. For example, when you ask Claude to "check my recent Jira tickets," the Claude Desktop client recognizes that it has an MCP server connected that handles Jira. It then sends a standardized request to that server to fetch the data.
The MCP Server
The server is a lightweight process that acts as a gateway to a specific set of capabilities. An MCP server does not "reason" on its own; instead, it exposes three main primitives:
- Tools: Executable functions that the AI can call to perform actions (e.g., "create_calendar_event", "search_database"). Tools have a defined input schema (usually JSON Schema) and return a result.
- Resources: Static or dynamic data sources that the AI can read (e.g., a local log file, a API response, or a database table). Resources are identified by URIs.
- Prompts: Pre-defined templates that help the AI perform specific tasks. These are like "system prompts" provided by the server to ensure the LLM uses the server's tools effectively.
The Transport Layer
Transports define how the client and server communicate. The most common transport is Stdio (Standard Input/Output), where the client starts the server as a child process and communicates via stdin/stdout. This is ideal for local tools. For remote servers, MCP supports HTTP with Server-Sent Events (SSE), allowing the AI to connect to cloud-hosted services.
Step-by-Step Implementation with TypeScript
Building an MCP server is streamlined thanks to the official TypeScript SDK. In this guide, we will build a "Developer Utility Server" that provides a tool to calculate project complexity and a resource to read a local project manifest.
Prerequisites and Project Setup
Ensure you have Node.js (v18+) and npm installed. We will use TypeScript for type safety and Zod for schema validation, as the SDK relies heavily on Zod to define tool inputs.
-
Initialize the project:
mkdir mcp-dev-server cd mcp-dev-server npm init -y npm install @modelcontextprotocol/sdk zod npm install -D typescript @types/node ts-node npx tsc --init -
Configure TypeScript: Set your
tsconfig.jsonto targetESNextand enableesModuleInteropto ensure compatibility with the SDK.
Creating the Server Instance
The entry point of any MCP server is the McpServer class. This class handles the protocol handshake and manages the registration of tools and resources.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
// Initialize the server
const server = new McpServer({
name: "DevUtilityServer",
version: "1.0.0",
});
Implementing a Tool: Project Complexity Calculator
Tools are the most powerful part of MCP. They allow the LLM to "do" things. We will implement a tool that takes a list of file counts and lines of code to return a complexity score.
server.tool(
"calculate_complexity",
"Calculates a project complexity score based on file counts and LOC",
{
fileCount: z.number().describe("Total number of source files"),
loc: z.number().describe("Total lines of code"),
},
async ({ fileCount, loc }) => {
const score = (loc / 100) * (fileCount / 5);
const rating = score > 100 ? "High" : score > 50 ? "Medium" : "Low";
return {
content: [{
type: "text",
text: `The project complexity score is ${score.toFixed(2)} (Rating: ${rating}).`
}],
};
}
);
In this snippet, the z.object (implied by the tool signature) ensures that the LLM provides the correct data types. If the LLM sends a string instead of a number, the SDK will automatically return a validation error, prompting the LLM to correct its request.
Implementing a Resource: Project Manifest Reader
While tools are for actions, resources are for data. Let's create a resource that exposes a project's package.json as a read-only document.
import fs from "node:fs/promises";
server.resource(
"project-manifest",
"The project's package.json manifest",
async (uri) => {
// In a real scenario, we would parse the URI to find the specific file
const content = await fs.readFile("./package.json", "utf-8");
return {
contents: [{
uri: uri.href,
mimeType: "application/json",
text: content,
}],
};
}
);
Connecting the Transport
Finally, we must tell the server how to communicate. For local development with the Claude Desktop app, we use the StdioServerTransport.
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("DevUtilityServer running on stdio");
}
main().catch((error) => {
console.error("Fatal error in main():", error);
process.exit(1);
});
Note: We use console.error for logging because console.log is reserved for the MCP protocol communication over stdout.
Testing and Deployment
To use your new server, you need to register it with an MCP client. For the Claude Desktop app on macOS, you would edit your configuration file:
~/Library/Application Support/Claude/claude_desktop_config.json
Add your server to the mcpServers object:
{
"mcpServers": {
"dev-utility": {
"command": "ts-node",
"args": ["/absolute/path/to/mcp-dev-server/index.ts"]
}
}
}
Restart Claude Desktop, and you should see a small "plug" icon indicating that the DevUtilityServer is active. You can now ask, "What is the complexity of my current project?" and Claude will call your calculate_complexity tool.
Best Practices and Security
When building MCP servers, security is paramount because you are effectively giving an LLM a way to execute code or read files on your system.
Input Validation
Never trust the input from the LLM. Always use Zod schemas to strictly validate types and ranges. If a tool accepts a file path, ensure the path is sanitized and restricted to a specific directory to prevent path traversal attacks.
Principle of Least Privilege
Your MCP server should run with the minimum permissions necessary. If it only needs to read a specific folder, do not run it as an administrator. If it interacts with an external API, use scoped API keys rather than master keys.
Error Handling
LLMs can be confused by raw stack traces. Wrap your tool logic in try-catch blocks and return user-friendly error messages. Instead of "Error: ENOENT: no such file or directory", return "The requested project manifest file could not be found in the expected location." This allows the LLM to apologize or try an alternative approach.
Conclusion
The Model Context Protocol is more than just a new SDK; it is a blueprint for a more interoperable AI future. By standardizing how tools and resources are exposed, MCP allows developers to focus on building valuable capabilities rather than fighting with API integrations. Whether you are building a simple local utility or a complex enterprise data gateway, the TypeScript SDK provides a robust foundation to extend the reach of AI models.
For further exploration, check out the official MCP Documentation and the TypeScript SDK Repository. You can also integrate these servers with models like Gemini 3.8 Live to create highly capable, context-aware agents.