# Model Context Protocol (MCP) Server Research
## 1. Introduction
The Model Context Protocol (MCP) is an open standard that enables AI models to securely interact with local and remote data sources and tools. It solves the "many-to-many" problem where every AI application needs its own integration for every data source. Instead, MCP provides a universal protocol for connection.
## 2. Architecture Overview
MCP follows a client-host-server architecture:
### Participants
- **MCP Host**: The AI application (e.g., Claude Desktop, IDEs) that coordinates the workflow. It manages connections to MCP servers and injects their context into the LLM.
- **MCP Client**: A component within the host that maintains the connection (1:1) with an MCP server using the protocol.
- **MCP Server**: A standalone service that exposes data (Resources), capabilities (Tools), and interaction templates (Prompts) via the MCP protocol.
### Layers
- **Transport Layer**: Handles the physical communication.
- **Stdio**: Standard Input/Output. Best for local servers.
- **SSE (Server-Sent Events) over HTTP**: Best for remote servers.
- **Data Layer (JSON-RPC 2.0)**: Use for message exchange.
- **Lifecycle**: Connection initialization (capabilities negotiation), health checks, termination.
- **Primitives**: The actual payload (Tools, Resources, Prompts).
## 3. Core Concepts (Primitives)
MCP Servers expose three main types of capabilities:
### 3.1 Tools (`tools/*`)
Executable functions that the LLM can invoke.
- **Purpose**: To perform actions or retrieve specific dynamic data (e.g., `get_weather(city)`, `query_database(sql)`).
- **Structure**: Name, Description, JSON Schema for arguments.
- **User Interaction**: Hosts typically require user approval before executing tools (especially for side-effects).
### 3.2 Resources (`resources/*`)
File-like data sources that can be read by clients context.
- **Purpose**: To provide context data (e.g., logs, file contents, database rows).
- **Addressing**: Identified by URIs.
- **Direct Resources**: Fixed URI (e.g., `file:///logs/app.log`).
- **Resource Templates**: Dynamic URI patterns (e.g., `postgres://users/{id}`).
- **Features**: Clients can `read` resources or `subscribe` to updates.
### 3.3 Prompts (`prompts/*`)
Reusable templates for LLM interactions.
- **Purpose**: To standardize workflows or "slash commands".
- **Structure**: Name, Description, Arguments.
- **Example**: A `review-code` prompt might take a `file_path` argument and inject a system prompt instructing the LLM on how to review that file.
## 4. Building an MCP Server (TypeScript)
This guide focuses on building a server using the Official TypeScript SDK.
### 4.1 Prerequisites
- Node.js (v18+)
- `@modelcontextprotocol/sdk`
- `zod` (for schema validation)
### 4.2 Step-by-Step Implementation
1. **Project Setup**
```bash
mkdir weather-mcp
cd weather-mcp
npm init -y
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node
```
2. **Server Initialization**
Create `src/index.ts`:
```typescript
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: "weather-server",
version: "1.0.0",
});
```
3. **Registering Tools**
Use `registerTool` to expose functions.
```typescript
server.tool(
"get_forecast",
{ latitude: z.number(), longitude: z.number() },
async ({ latitude, longitude }) => {
// Implementation logic (e.g., fetch external API)
const forecast = `Sunny at ${latitude},${longitude}`;
return {
content: [{ type: "text", text: forecast }],
};
}
);
```
4. **Registering Resources**
Use `resource` to expose data.
```typescript
server.resource(
"config-file",
"config://app/settings",
async (uri) => {
return {
contents: [{
uri: uri.href,
text: JSON.stringify({ theme: "dark" }),
mimeType: "application/json"
}]
};
}
);
```
5. **Running the Server**
Connect the server to a transport (usually Stdio for local use).
```typescript
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Weather MCP Server running on stdio");
}
main().catch((error) => {
console.error("Fatal error:", error);
process.exit(1);
});
```
### 4.3 Best Practices
- **Logging**: **NEVER** use `console.log()` for debugging if using Stdio transport, as it corrupts the JSON-RPC messages on stdout. Use `console.error()` which writes to stderr.
- **Error Handling**: Return graceful error messages in tool responses rather than crashing.
- **Security**: Validate all inputs using Zod schemas. Do not expose sensitive internal files via Resources without validation.
## 5. Summary
MCP provides a structured standard for AI extendability. By implementing an MCP server, developers can "write once, run everywhere" for any MCP-compliant host (Claude, IDEs, Agentic Workflows). The core building blocks—Resources for context, Tools for action, and Prompts for workflows—cover most AI integration use cases.