Your First MCP Server
🎯 Introduction
The previous article introduced MCP's communication architecture and tool call flow. Here, we will build an HTTP MCP server with Express, expose a product stock lookup tool, write a Node.js MCP client to discover and call it, and finally connect the server to Cursor.
To focus on MCP development, we will use fixed stock data instead of a real business API. Writing and testing the server does not require a model call.
🛠 Create the Project
This course uses Node.js 24 LTS and the official MCP TypeScript SDK v2. Examples use JavaScript ESM, which the SDK also supports.
Create the project and install its dependencies:
mkdir mcp-demo
cd mcp-demo
npm init -y
npm install --save-exact @modelcontextprotocol/server@2.3.0 @modelcontextprotocol/client@2.3.0 zod@4.2.1 @modelcontextprotocol/express@2.0.2 @modelcontextprotocol/node@2.1.0 express@5.1.0
| Dependency | Purpose |
|---|---|
@modelcontextprotocol/server | Create MCP servers and register tools |
@modelcontextprotocol/client | Connect to MCP servers, discover tools, and call them |
zod | Define and validate tool arguments |
express | Create an HTTP service |
@modelcontextprotocol/express | Provide a preconfigured Express application |
@modelcontextprotocol/node | Adapt MCP HTTP handlers to Node.js |
🧱 Create an MCP Server
Create 02.first-server.mjs in the project root:
import { McpServer } from "@modelcontextprotocol/server";
function createServer() {
const server = new McpServer({
name: "first-shop",
version: "1.0.0"
});
return server;
}
McpServer is the SDK class for creating an MCP server instance. name and version identify our server and its version; clients can retrieve this information when connecting.
We wrap server creation in createServer(). Later, the SDK will use this function to create server instances with their tools already registered.
🧱 Register a Stock Lookup Tool
Our server should provide a tool for checking product stock. Registration requires three pieces of information:
- Tool name:
get_stock. - Tool definition: the tool's purpose and accepted arguments.
- Execution function: returns stock information for the supplied product ID.
The SDK provides registerTool() to register tools.
Define and Register the Tool
Add the Zod import at the top of 02.first-server.mjs:
import { z } from "zod";
Inside createServer(), before return server, add:
server.registerTool(
"get_stock",
{
description: "Look up stock for product P100",
inputSchema: z.object({
id: z.literal("P100")
})
},
async ({ id }) => {
return {
content: [{
type: "text",
text: `${id} has 12 units in stock`
}]
};
}
);
Tool Definitions and Argument Validation
description explains what the tool does. AI applications can give this description to the model to help it decide when to use the tool.
inputSchema defines the accepted arguments. Here, Zod's z.object() defines their structure, and z.literal("P100") restricts id to P100 because this article only has stock data for that product.
The SDK converts the Zod definition to JSON Schema so clients can retrieve tool information. It also validates incoming arguments before executing the tool function. For example, passing P200 will not execute the stock lookup function.
Tool Execution and Results
The third argument is the execution function. When get_stock is called, the SDK passes the validated arguments to this function. Here it returns fixed stock data; the next article connects it to a real business API.
Why not simply return 12? The execution function must return data using MCP's tool result structure:
| Property | Purpose |
|---|---|
content | Contains one or more content blocks returned by the tool |
type | The content block type; text indicates text |
text | The returned text, such as P100 has 12 units in stock |
This lets clients read tool results in a consistent format.
🧱 Serve MCP over HTTP
The tool is registered, but no HTTP endpoint can receive client requests yet. Next, connect the MCP server to Express.
Create a Request Handler
At the top of 02.first-server.mjs, replace the McpServer import with:
import { McpServer, createMcpHandler } from "@modelcontextprotocol/server";
Add two more imports:
import { createMcpExpressApp } from "@modelcontextprotocol/express";
import { toNodeHandler } from "@modelcontextprotocol/node";
Outside createServer(), at the end of the file, add:
const handler = createMcpHandler(createServer);
const nodeHandler = toNodeHandler(handler);
createMcpHandler() takes the server factory and creates a request handler for MCP HTTP messages. In this example, the SDK creates a server instance for each request.
The handler uses the Web-standard Request and Response interfaces, whereas Express uses Node.js request and response objects. toNodeHandler() adapts these interfaces so the MCP handler can be used in an Express route.
Register the HTTP Route
Continue at the end of the file:
const app = createMcpExpressApp();
app.all("/mcp", (req, res) => {
void nodeHandler(req, res, req.body);
});
app.listen(3200, "127.0.0.1", () => {
console.log("MCP Server: http://127.0.0.1:3200/mcp");
});
createMcpExpressApp() creates an Express application with JSON body parsing and local request security checks configured. Since Express has already parsed the body, pass req.body to the handler.
/mcp is the shared protocol endpoint. Tool discovery and calls both send messages to this address, and the SDK handles them according to their contents. There is no separate route for get_stock. app.all() forwards the path's different HTTP methods to the SDK.
Start the Service
Run from the project root:
node 02.first-server.mjs
Expected output:
MCP Server: http://127.0.0.1:3200/mcp
Keep this terminal running and use another terminal for the client. This example listens only on the local address and has no authentication configured. Do not expose it directly to the public internet.
🧱 Create an MCP Client
An MCP client normally runs inside a host such as Cursor. To study discovery and calls directly, we will write a standalone Node.js client script without involving a model.
Create 02.first-client.mjs in the project root. The main files are now as follows (dependencies and lockfiles omitted):
mcp-demo/
├── package.json
├── 02.first-server.mjs
└── 02.first-client.mjs
Create a Client Instance
In 02.first-client.mjs, write:
import { Client } from "@modelcontextprotocol/client";
const client = new Client({
name: "shop-client",
version: "1.0.0"
});
Client creates an MCP client instance. name and version identify the client itself and its version.
Connect to the Server
Since the server uses HTTP, the client needs an HTTP transport.
Replace the Client import at the top of the file with:
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
At the end of the file, add:
const transport = new StreamableHTTPClientTransport(
new URL("http://127.0.0.1:3200/mcp")
);
try {
await client.connect(transport);
} finally {
await client.close();
}
StreamableHTTPClientTransport takes the server URL. Calling connect() establishes MCP communication over HTTP with the running server.
Place the following tool discovery and call code inside try, after connect(). The close() in finally closes the client connection and attempts cleanup even if an operation fails. It does not stop the independently running HTTP server.
🧱 Discover and Call Tools
List Tools
After connecting, inspect the tools the server provides. Inside try, after await client.connect(transport), add:
const { tools } = await client.listTools();
console.log(JSON.stringify(tools, null, 4));
listTools() corresponds to MCP's tools/list operation. The returned tools include names, descriptions, and argument definitions. JSON.stringify() prints the complete nested argument structure.
With the server still running, run this from the project root in another terminal:
node 02.first-client.mjs
The key fields in the expected output are shown below. Actual output may include additional fields:
[
{
"name": "get_stock",
"description": "Look up stock for product P100",
"inputSchema": {
"type": "object",
"properties": {
"id": {
"type": "string",
"const": "P100"
}
},
"required": ["id"]
}
}
]
The server's Zod argument definition has become JSON Schema. const requires the value P100, and required makes id mandatory.
This is tool discovery: the client learns which tools exist and how to pass arguments without inspecting the server's source code.
Call the Stock Lookup Tool
We now know which arguments get_stock takes, but have not checked stock yet. Use callTool() to execute the lookup.
Inside try, after the code that prints the tool list, add:
const result = await client.callTool({
name: "get_stock",
arguments: {
id: "P100"
}
});
console.log(JSON.stringify(result, null, 4));
callTool() corresponds to MCP's tools/call operation. name identifies the tool, and arguments contains its arguments.
Run the client again:
node 02.first-client.mjs
In addition to the tool list, it should print this tool result (key fields shown):
{
"content": [
{
"type": "text",
"text": "P100 has 12 units in stock"
}
]
}
content is what the tool's execution function returned on the server. Seeing the stock information confirms that the client called the tool and received its result.
Here, we specify the tool name and arguments ourselves. In an AI application, the host can fill in these fields using the model's tool call response.
🧰 Use Your MCP Server in Cursor
Next, let Cursor use the stock lookup tool to experience how an AI application handles tool calls. This step is optional and does not affect later articles.
Configure the MCP Server
Open the mcp-demo folder in Cursor and create .cursor/mcp.json in the project root:
{
"mcpServers": {
"shop": {
"url": "http://127.0.0.1:3200/mcp"
}
}
}
shop is the server's configuration name in Cursor, and url is the MCP service address started earlier. Keep the server running; no local script startup command is needed.
Connect and Call the Tool
Open Cursor's MCP tool settings, confirm that shop is enabled, and check that get_stock appears. The location of these settings may vary by Cursor version.
In a chat mode that supports tool calls, enter:
Use shop's get_stock tool to check the stock for P100.
If a tool authorization prompt appears, check the tool name and arguments before allowing execution.
The tool should return 12 units in stock. The model might answer, “Product P100 has 12 units in stock.” Actual behavior and wording depend on Cursor's mode, configuration, and model.
Unlike our standalone client, Cursor is a host that also interacts with the model. Here, the model requests the tool call, and Cursor's internal MCP client calls the server.
References: Official MCP TypeScript SDK v2, Express integration, client connections.
mcp-demo project, 02.first-server.mjs, and 02.first-client.mjs, adding capabilities to the existing service. After changing the server, press Ctrl+C to stop it, then run node 02.first-server.mjs again. The client continues connecting to the same /mcp address.❓ Knowledge Check
Q1: Why doesn't running node 02.first-server.mjs print a stock result?
The server is waiting for requests. It only executes the lookup when a client calls get_stock. The tool result is returned to the client through MCP messages, rather than printed as an ordinary log.
🧪 Exercise
- Change the
idin the client'scallTool()to"P200". Run it again and inspect the failure result or exception. Change it back to"P100"and verify that the call succeeds. - Register a
get_pricetool insidecreateServer(). It should accept only product ID P100 and return a fixed price of CNY 299. Restart the server and run the client to confirm that the tool list contains two tools. Then change the tool name incallTool()toget_priceand verify the price result.
🎉 You have built your first MCP server and discovered and called its tool through a Node.js client. Next, we will connect a real business API to query product data.
