MCP Server That Calls Real HTTP APIs: Error Handling and What Actually Matters
MCP Practice (Part 2): Making Your Own MCP Server Call Real HTTP Interfaces
Author: 陆枫Larry Tags: 人工智能
In the previous article, I recorded my first experience learning MCP concepts: from initially not understanding what MCP Client and MCP Server are, to using the official file system tool, and then developing my own mathServer that Copilot and OpenCode successfully called. That gave me a preliminary understanding of MCP.
However, the mathServer I wrote before only had a simple addition function:
const result = a + b;
Although it successfully ran the complete MCP calling flow, it still felt a bit far from actual business scenarios. After all, in daily development, we often deal with user data, order information, database queries, and other backend interfaces that call real environments.
So this time I decided to continue with a small experiment: develop my own userServer and let Copilot call a real HTTP API through MCP to query user information.
I also wanted to investigate how an MCP Server should handle abnormal situations such as the interface returning 404, network connection failures, or request timeouts.
1. Clarify What We're Doing This Time
The goal this time is actually simple: I want to directly say to Copilot, "Help me query the user information with ID 1." Then Copilot selects the tool, queries the HTTP interface through the MCP Server, and finally returns the user data.
The entire calling flow is as follows:
User raises a natural language request
↓
Copilot understands the request
↓
MCP Client calls getUserInfo
↓
userServer receives parameters
↓
fetch() requests the HTTP API
↓
Interface returns JSON
↓
MCP Server returns tool result
↓
Copilot organizes and answers
There is a point worth noting here: our developed userServer acts as an MCP Server when facing Copilot, and as an HTTP Client when facing external HTTP APIs.
These two identities do not conflict, because client and server are always relative to a specific communication. Once you understand this, it becomes much easier to understand the code later.
2. Create an Independent user-mcp Project
Previously, we developed math-mcp, so this time I didn't add the user query tool to it but created a new user-mcp project.
The reason is simple: mathematical calculations and user information queries are two different business capabilities, and separating them makes organization clearer. Of course, this is not a mandatory requirement of MCP. Real projects also need to consider business scale, permissions, and maintenance costs; there's no need to split things just for the sake of splitting.
Now let's get into the practical steps:
Create the project:
mkdir user-mcp cd user-mcp npm init -y
Set up ES Module:
npm pkg set type=module
Install dependencies:
npm install @modelcontextprotocol/server zod tsx
These three dependencies are responsible for MCP Server development, parameter validation, and TypeScript execution, respectively.
Finally, create the entry file:
mkdir -p src touch src/index.ts
The entire project structure is as follows:
user-mcp/ ├── node_modules/ ├── src/ │ └── index.ts ├── package.json └── package-lock.json
This time I also revisited the role of package-lock.json: package.json mainly describes which dependencies the project needs, while package-lock.json records the actually resolved dependency versions and relationships.
Once the project is committed to Git, other developers can use npm ci to install a consistent dependency environment as much as possible, without having to upload the entire node_modules folder.
This knowledge isn't directly related to MCP, but it's commonly encountered in actual development, so I'm noting it as a small tip.
3. Register the getUserInfo Tool
Next, let's write the MCP Server.
First, create the Server instance:
import { McpServer } from "@modelcontextprotocol/server"; import { serveStdio } from "@modelcontextprotocol/server/stdio"; import * as z from "zod/v4";
const server = new McpServer({ name: "user-demo", version: "1.0.0", });
Then, register a tool:
server.registerTool( "getUserInfo", { description: "Query user information by user ID", inputSchema: z.object({ userId: z.number() .int() .positive() .describe("The user ID to query"), }), }, async ({ userId }) => { // Query logic temporarily omitted return { content: [ { type: "text", text:
Received user ID: ${userId}, }, ], }; } );
This code is basically similar to the previous math tool.
I think the most noteworthy part is inputSchema: it specifies that userId must be a number, an integer, and greater than 0.
userId: z.number().int().positive()
Here it's important to distinguish a concept that's easy to confuse: parameter validation is not the same as automatic parameter conversion.
For example, z.number() requires a real number like 123; it won't automatically convert the string "123" into a number. If you need conversion, you could consider Zod's z.coerce.number(), but conversion rules also need careful handling. The tool's parameter definition is not only for validation by the MCP Server but also becomes important description information when clients discover the tool.
4. Make the Tool Actually Call the HTTP API
Next, we get to the core of this experiment:
I chose the public test interface provided by JSONPlaceholder:
https://jsonplaceholder.typicode.com/users/1
It doesn't require an API Key and directly returns mock user data, making it great for experiments. Before calling MCP, I tested it via the terminal:
curl -i https://jsonplaceholder.typicode.com/users/1
Returned:
HTTP/2 200
The response also contains user information like this:
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]"
}
This step seems ordinary, but I think it's quite necessary. Because if a query through MCP fails later, at least I already know the HTTP interface itself is accessible. This way, when troubleshooting, we can first distinguish between the HTTP layer and the MCP layer, rather than attributing all errors to MCP.
Then, I changed the getUserInfo callback to actually call the interface:
async ({ userId }) => {
const response = await fetch(
`https://jsonplaceholder.typicode.com/users/${userId}`
);
if (!response.ok) {
return {
isError: true,
content: [
{
type: "text",
text: `Query failed, HTTP status code: ${response.status}`,
},
],
};
}
const user = await response.json();
return {
content: [
{
type: "text",
text: JSON.stringify(user, null, 2),
},
],
};
}
This is the biggest difference between this experiment and the previous mathServer:
Previously, the tool's internal logic only executed:
a + b
Now it executes:
await fetch(url)
But for the MCP Client, both business implementations are encapsulated as callable MCP Tools.
This is where I begin to understand the engineering value of MCP.
5. Connecting to Copilot: First Successful Query
After writing the tool, I started the MCP communication via serveStdio:
void serveStdio(() => server);
Because the stdio transport method is used, there's no need to write app.listen(3000).
Next, I added the userServer configuration in .mcp.json in VS Code.
The core content of the configuration is roughly as follows:
{
"userServer": {
"type": "stdio",
"command": "/your-project-path/user-mcp/node_modules/.bin/tsx",
"args": [
"/your-project-path/user-mcp/src/index.ts"
]
}
}
This is the configuration snippet that needs to be merged into the existing mcpServers object. After saving, VS Code displays:
userServer
Running | Stop | 1 tool
This indicates that the MCP Server has started, and Copilot discovered one tool.
Next, I asked Copilot: "Please use the getUserInfo tool of userServer to query the user information with ID 1."
This time, Copilot successfully called:
userServer-getUserInfo
With the parameter:
{
"userId": 1
}
Finally, it returned the user information:
Name: Leanne Graham
Username: Bret
Email: [email protected]
The first time I saw this, I felt the whole idea finally connected to daily development: previously, a Vue page would use Axios to request a Java backend. Now, AI selects an MCP Tool based on natural language, and the MCP Server makes an HTTP request to an external interface.
The HTTP API hasn't changed; what changed is who calls it and how the calling entry point is discovered by AI.
6. Successful Query Works, What About Error Cases?
At this point, the basic functionality is implemented. However, only verifying the normal case isn't enough. In real business, interfaces don't always return 200. So I ran a few more experiments:
1. Querying a Nonexistent User
This time I asked Copilot to query: "information for user ID 99999."
JSONPlaceholder returned HTTP 404.
Our previous code uses:
if (!response.ok)
to判断非成功状态, and through:
isError: true
indicates to the MCP Client that the tool execution failed.
Copilot correctly displayed the error, without fabricating a nonexistent user.
However, the initial message was:
Query failed, HTTP status code: 404
This message is fine for developers, but not friendly enough for ordinary users.
So I modified the error handling:
if (!response.ok) {
const message =
response.status === 404
? `User with ID ${userId} not found`
: `User query failed, HTTP status code: ${response.status}`;
return {
isError: true,
content: [
{ type: "text" as const, text: message },
],
};
}
After the modification, I restarted the MCP Server and queried user ID 99999 again.
This time Copilot displayed:
User with ID 99999 not found
This experiment also clarified a distinction:
An HTTP request failure does not mean an MCP communication failure.
The communication between MCP Client and MCP Server can be perfectly normal; it's just that the HTTP interface accessed inside the tool returned a business error. These are two different levels of problems.
2. Simulating Network Connection Failure
404 is a response explicitly returned by the server. But what if the server can't be connected to at all?
In that case, fetch() might throw an exception directly rather than returning a response object. Therefore, a try...catch is needed.
So I added timeout control to the HTTP request:
const response = await fetch(
`https://jsonplaceholder.typicode.com/users/${userId}`,
{
signal: AbortSignal.timeout(5000),
}
);
Here, AbortSignal.timeout(5000) sets a 5-second timeout period.
Then, capture the exception with catch:
catch (error) {
const isTimeout =
error instanceof Error &&
error.name === "TimeoutError";
const message = isTimeout
? "Query timed out, please try again later"
: "Network request failed, please check your network connection";
return {
isError: true,
content: [
{ type: "text" as const, text: message },
],
};
}
To verify this code, I temporarily changed the normal interface address to:
http://127.0.0.1:65534/users/1
This is a local address; I chose a test port where I expected no service to be listening. After saving the code and restarting the MCP Server, I asked Copilot to query user ID 1 again.
The result: Copilot's tool execution record showed a failure and returned:
Network request failed, please check your network connection
This shows that the connection exception thrown by fetch() was caught by catch and correctly returned as error information through the MCP Tool.
It should be noted that this test verified connection failure handling, but I haven't specifically simulated a request exceeding the 5-second timeout scenario. Although the timeout control code has been written, the corresponding exception branch is still worth verifying separately in the future.
3. Restoring the Normal Interface and Running a Regression Test
After simulating network errors, I restored the URL to:
https://jsonplaceholder.typicode.com/users/1
Restarted the MCP Server, and asked Copilot to query user ID 1 again. The result correctly returned Leanne Graham's user data. This step is essentially the simplest regression test.
After adding error handling, we also confirmed that the original normal functionality was not affected.
At this point, all three scenarios - success, 404, and connection failure - have been verified.
7. What I Understood from This Practice
Looking back, I didn't write much code this time, but the takeaways are quite substantial.
First, MCP is not responsible for understanding natural language.
The AI model is what understands user needs.
After the model decides to call getUserInfo, the MCP Client passes structured parameters to the Server, and what actually executes the HTTP request is ordinary code inside the Server.
Second, MCP and HTTP API are not contradictory.
Previously, I always wanted to compare MCP and API to see which was more useful. Later, I found that they are not substitutes for each other.
HTTP APIs still provide business capabilities. MCP can wrap these capabilities as standard tools, allowing compatible AI applications to discover and call them.
If the existing system already has mature Java backend interfaces, you can continue to reuse them without rewriting business logic for AI integration.
Third, MCP Tools must also be developed according to normal software engineering requirements.
Just because a tool can be called by AI doesn't mean it automatically becomes reliable and secure. Parameter validation, exception handling, request timeouts, identity authentication, and permission control - none of these issues will simply disappear. Especially when dealing with real business data, you can't assume that just because AI can call a tool, it automatically has permission to access all the data behind that tool.
Fourth, pay attention to the process lifecycle of the MCP Server after modifying code.
In this experiment, every time I modified index.ts, I needed to restart userServer. That's because I used the normal tsx startup method without hot reload. This is similar to how modifying Java backend code requires redeployment or service restart.
8. Final Thoughts
After two MCP practice sessions, my understanding is much clearer than at the beginning.
The first practice mainly solved the problem of "how to connect and call tools." This time, I went a step further: making my own MCP Server actually request HTTP APIs and gradually handle interface exceptions.
From calling an addition function to accessing a real HTTP interface, this is essentially pushing MCP from a simple teaching example a small step closer to actual business scenarios.
At present, this user-mcp is still just an experimental project. There's still a lot to do before it can be used in real business, such as response data structure validation, sensitive field filtering, identity authentication, permission control, and more complete error and timeout testing.
However, I don't think it's necessary to implement all of these at once right now. First, understand how MCP runs, then understand how it works with HTTP APIs, and finally gradually add engineering capabilities. This way, learning is more solid.
Next, I plan to continue researching MCP's remote communication methods, especially Streamable HTTP, and see how it differs from the current stdio.
I'll record that next time.