Overview
Level 3: Advanced · Module 7: Tool Calling, Agents, and MCP · 25 min read
Why this matters
Before late 2024, every AI product implemented custom, non-standard tool abstractions: if you built a GitHub tool for OpenAI, you had to rewrite it completely for Claude, and rewrite it again for LangChain or your custom Next.js agent. Anthropic's Model Context Protocol (MCP) changes this by establishing an open, standardized JSON-RPC 2.0 communication protocol connecting AI clients (hosts) to external data sources, prompts, and tools (servers). Today, major development tools (Claude Desktop, Cursor, Antigravity IDE) and cloud backends natively support MCP servers. Learning to architect, build, and connect MCP servers gives frontend engineers portable, reusable agent integrations across any AI client.
Learning objectives
- Understand the core primitives of MCP: Resources, Prompts, and Tools.
- Learn the Client-Host-Server architecture of MCP.
- Contrast MCP Transports:
stdio(local subprocess) vsSSE/ WebSockets (remote server). - Build a typed MCP server in TypeScript using the official
@modelcontextprotocol/sdk. - Connect Next.js applications as both MCP clients and MCP server providers.
The MCP Architecture: Host, Client, and Servers
graph TD
subgraph HostApp["MCP Host / Client (Next.js App / Cursor / Claude Desktop)"]
Client["MCP Client Core"]
end
subgraph Transports["Transports Layer (JSON-RPC 2.0)"]
Stdio["stdio Transport<br>(Spawns local CLI subprocess)"]
SSE["SSE / HTTP Transport<br>(Connects over remote network)"]
end
subgraph MCPServers["Modular MCP Servers (Standardized Ecosystem)"]
Server1["GitHub MCP Server<br>(Repos, PRs, Issues)"]
Server2["Postgres MCP Server<br>(Schema, Read queries)"]
Server3["Figma / Filesystem Server<br>(Design tokens, Local assets)"]
end
Client --> Stdio
Client --> SSE
Stdio --> Server1
Stdio --> Server3
SSE --> Server2The Three Foundational MCP Primitives
- Tools: Executable functions that perform operations or state mutations (e.g.
create_issue,run_query). Require model-driven tool calling. - Resources: Passive read-only data files or database schemas exposed to the context window (e.g.
file:///schema.prismaorpostgres://customers/schema). Handled like file attachments. - Prompts: Pre-configured prompt templates with dynamic arguments exposed by the server for standard agent workflows (e.g.
debug_pr(pr_number)).
Implementation: Writing an MCP Server in TypeScript
Here is a complete, working MCP server exposing a Postgres database tool using the official @modelcontextprotocol/sdk:
// server/mcp-server.ts
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
// 1. Initialize MCP Server instance
const server = new Server(
{
name: "ecommerce-catalog-server",
version: "1.0.0",
},
{
capabilities: {
tools: {},
resources: {},
},
}
);
// 2. Register available tools
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "search_products",
description: "Search e-commerce product catalog by keyword and category.",
inputSchema: {
type: "object",
properties: {
keyword: { type: "string", description: "Search query" },
category: { type: "string", description: "Optional product category" },
},
required: ["keyword"],
},
},
],
};
});
// 3. Handle tool invocation
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === "search_products") {
const { keyword, category } = request.params.arguments as any;
// Simulated query
const results = [
{ id: "p1", name: "Wireless Mechanical Keyboard", price: 129.99 },
{ id: "p2", name: "Ergonomic Vertical Mouse", price: 79.99 },
];
return {
content: [
{
type: "text",
text: JSON.stringify(results, null, 2),
},
],
};
}
throw new Error(`Tool not found: ${request.params.name}`);
});
// 4. Connect via stdio transport (Subprocess IPC)
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("🚀 MCP Server running on stdio!");
}
main().catch(console.error);Connecting to an MCP Server from Next.js (SSE Transport)
For remote web applications, the client connects over Server-Sent Events (SSE) rather than local subprocess stdio:
// lib/mcp/client.ts
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
export async function createMcpClient() {
const client = new Client(
{ name: "nextjs-web-client", version: "1.0.0" },
{ capabilities: {} }
);
// Connect to remote MCP server over HTTP/SSE
const transport = new SSEClientTransport(
new URL("https://mcp.internal.mycompany.com/sse")
);
await client.connect(transport);
// Discover server tools dynamically!
const tools = await client.listTools();
console.log(`[MCP] Discovered ${tools.tools.length} remote tools.`);
return { client, tools };
}Interview Angle: How to Answer in System Design
- Question: "What is the Model Context Protocol (MCP) and why is it replacing ad-hoc tool integrations?"
- Target Answer:
"Prior to MCP, every AI framework and LLM client implemented proprietary tool schemas, creating an $M \times N$ integration matrix: each tool had to be rewritten for every client.
MCP introduces an open standard over JSON-RPC 2.0 that decouples AI Hosts/Clients (Claude Desktop, Next.js agents, Cursor) from Tool Servers (GitHub, Postgres, Slack).
An MCP server exposes three standard primitives: Tools (executable functions), Resources (read-only documents and data files), and Prompts (curated templates). By writing an MCP server once, our internal company APIs can be plugged into our web apps, developer IDEs, and desktop AI clients with zero custom glue code."
Quick Check
- What protocol does the Model Context Protocol (MCP) use under the hood?
- What are the three core primitives exposed by an MCP server?
- When would you choose the
SSEtransport over thestdiotransport for an MCP server?