Tools
🎯 Introduction
The stock lookup tool in the previous article returned fixed data. In practice, MCP tools usually request business APIs, query databases, or perform other business operations.
Using product lookups, this article wraps a REST API as MCP tools and covers argument validation, structured data, missing products, and failed API requests.
🛠 Prepare the Product API
To make the tool perform an actual business query, we will build a local product service with Express. Its data stays in memory, so no database installation is needed.
Continue using the mcp-demo project.
Create business-api.mjs:
import express from 'express';
const app = express();
const products = [
{ id: 'P100', name: 'Mechanical Keyboard', stock: 12, price: 199 },
{ id: 'P200', name: 'Wireless Mouse', stock: 0, price: 89 },
];
app.get('/products/:id', (req, res) => {
const product = products.find(item => item.id === req.params.id);
if (!product) {
return res.status(404).json({ message: 'Product not found' });
}
res.json(product);
});
app.listen(3100, '127.0.0.1', () => {
console.log('Product API: http://127.0.0.1:3100');
});
Run:
node business-api.mjs
Keep this terminal running and open http://127.0.0.1:3100/products/P100 in a browser. The expected response is:
{
"id": "P100",
"name": "Mechanical Keyboard",
"stock": 12,
"price": 199
}
The tools below will retrieve product data through this API.
🧱 Extract the Business Query Function
We will develop two tools: stock lookup and product details. Both request the same product API, so first extract the query logic into a shared function.
Create shop.mjs in the project root and wrap the product API request in getProduct():
export async function getProduct(id) {
const response = await fetch(`http://127.0.0.1:3100/products/${encodeURIComponent(id)}`, {
signal: AbortSignal.timeout(5000),
});
if (response.status === 404) {
throw Object.assign(new Error('Product not found'), { code: 'PRODUCT_NOT_FOUND' });
}
if (!response.ok) {
throw new Error('Product API request failed');
}
return await response.json();
}
getProduct() is an ordinary business function independent of MCP. It returns a product object on success and throws on failure. For missing products, it also sets the PRODUCT_NOT_FOUND error code so we can distinguish failure causes later.
🧱 Register the Stock Lookup Tool
Define the Tool
Previously, z.literal("P100") restricted product IDs to P100. The API now supports multiple products, so accept strings starting with P followed by one or more digits.
Add this import at the top of the existing 02.first-server.mjs:
import { getProduct } from './shop.mjs';
Outside createServer(), add the argument schema:
const productInputSchema = z.object({
id: z
.string()
.regex(/^P\d+$/)
.describe('Product ID, such as P100'),
});
Inside createServer(), replace the existing get_stock registration with:
server.registerTool(
'get_stock',
{
description: 'Look up the current stock quantity by product ID',
inputSchema: productInputSchema,
},
async ({ id }) => {
const product = await getProduct(id);
return {
content: [
{
type: 'text',
text: `${product.name} has ${product.stock} units in stock`,
},
],
};
}
);
Extracting productInputSchema lets the product details tool reuse it later.
description explains the tool's purpose so the model can decide when to select it. The argument's .describe() helps the model understand which value to supply for id.
When called, the tool requests the product API through getProduct(id) and formats the returned stock quantity as text.
Call the Stock Lookup Tool
In the existing 02.first-client.mjs, keep connection and cleanup code. Replace the tool-listing and call code after await client.connect(transport) inside try with:
const result = await client.callTool({
name: 'get_stock',
arguments: { id: 'P200' },
});
console.log(JSON.stringify(result, null, 2));
Keep the product API running, restart the MCP server, then run the client:
node 02.first-client.mjs
The key fields in the expected result are shown below (subsequent outputs also show only key fields):
{
"content": [
{
"type": "text",
"text": "Wireless Mouse has 0 units in stock"
}
]
}
A stock quantity of 0 is a successful query result: the product exists but is out of stock.
🧱 Argument Validation
inputSchema both exposes the tool's argument definition to clients and lets the server validate arguments before execution. If validation fails, the execution function does not run and the product API is not requested.
Change id in the client's callTool() to ABC and run it again:
node 02.first-client.mjs
Expected result (the error wording is simplified):
{
"isError": true,
"content": [
{
"type": "text",
"text": "Input validation error: id does not meet the argument constraints"
}
]
}
isError: true indicates that the tool call failed, and content explains why. Although the client received a result, the server did not execute the stock lookup.
Argument validation checks the ID format, not whether a product exists:
| Argument | Validation | Business query |
|---|---|---|
P200 | Passes | 0 units in stock |
P999 | Passes | Product not found |
ABC | Fails | Query not executed |
The failure for P999 is a business execution error, which we will handle later.
🧱 Return Structured Data
Register a Product Details Tool
The stock tool returns text. For complete product information, applications may need to access properties such as price and stock. Although an object can be serialized to JSON text and parsed again, MCP also supports returning structured data directly.
Inside createServer() in 02.first-server.mjs, before return server, add:
server.registerTool(
'get_product',
{
description: 'Look up the name, price, and stock by product ID',
inputSchema: productInputSchema,
outputSchema: z.object({
id: z.string(),
name: z.string(),
stock: z.number(),
price: z.number(),
}),
},
async ({ id }) => {
const product = await getProduct(id);
return {
content: [
{
type: 'text',
text: JSON.stringify(product),
},
],
structuredContent: product,
};
}
);
Compared with the stock tool, the product details tool adds structured data:
| Property | Purpose |
|---|---|
outputSchema | Defines and validates structured data returned on success |
structuredContent | Contains the actual structured data |
content | Retains a text result for applications that only read text content |
outputSchema validates structuredContent, not the text in content. A result with isError: true does not need to match the success output schema.
Call the Product Details Tool
Save 02.first-server.mjs, stop it, and run node 02.first-server.mjs again to activate the new tool. Keep the product API running.
In 02.first-client.mjs, change the callTool() name to get_product and id to P100, then replace the logging statement with:
console.log(JSON.stringify(result.structuredContent, null, 2));
Run it again:
node 02.first-client.mjs
Expected output:
{
"id": "P100",
"name": "Mechanical Keyboard",
"stock": 12,
"price": 199
}
result.structuredContent is an object, so applications can read result.structuredContent.price directly without parsing the JSON text in content.
⚠️ Handle Tool Call Failures
Execution Exceptions
A business query can fail even when arguments have the correct format: the product might not exist, the API might be stopped, or the request might time out.
Change the client's name back to get_stock, set id to P999, restore console.log(JSON.stringify(result, null, 2)), and run:
node 02.first-client.mjs
Key fields in the expected result:
{
"isError": true,
"content": [
{
"type": "text",
"text": "Product not found"
}
]
}
P999 passes argument validation, but the product API returns 404 and getProduct() throws. The SDK catches exceptions from the execution function and converts them to tool error results. Unlike the earlier validation failure, this time the execution function ran and requested the product API.
Custom Error Results
By default, the SDK uses the exception message for the error result. To give callers clearer guidance, catch exceptions inside the execution function and return your own error result. Earlier, getProduct() assigned a code to missing-product errors. We use that code to distinguish missing products from other query failures without relying on error wording.
In 02.first-server.mjs, replace the third argument to get_stock (its execution function) with:
async ({ id }) => {
try {
const product = await getProduct(id);
return {
content: [
{
type: 'text',
text: `${product.name} has ${product.stock} units in stock`,
},
],
};
} catch (error) {
const message =
error.code === 'PRODUCT_NOT_FOUND'
? 'Product not found. Check the product ID.'
: 'Product lookup failed. Try again later.';
return {
isError: true,
content: [{ type: 'text', text: message }],
};
}
}
This provides actionable guidance while avoiding direct exposure of internal details from underlying request exceptions.
Save 02.first-server.mjs and restart the MCP server (node 02.first-server.mjs). Keep the P999 call in the client and replace its logging statement with:
if (result.isError) {
console.log('Call failed:', result.content[0].text);
} else {
console.log('Call succeeded:', result.content[0].text);
}
Run:
node 02.first-client.mjs
Expected output:
Call failed: Product not found. Check the product ID.
If the product API is unreachable, the execution function returns “Product lookup failed. Try again later.” Successful results keep the same structure.
How Should the Client Handle Errors?
Receiving a result from callTool() does not guarantee business success, so clients must check result.isError. Connection failures, timeouts, or calls to nonexistent tools can also cause the SDK to throw directly, without returning a normal tool result.
In the client, replace the existing } finally { ... } section with the following, keeping the call and result check inside try:
} catch (error) {
console.error("MCP request failed:", error.message);
} finally {
await client.close();
}
For example, change the client's name to the unregistered get_unknown and run it again. Execution enters catch and prints a request failure instead of reaching the result.isError branch. Restore the name to get_stock after testing.
References: MCP SDK Tools documentation, error handling.
❓ Knowledge Check
Q1: Does passing argument validation guarantee successful tool execution?
No. Validation only checks input constraints. Execution can still fail because a product is missing, an API request fails, or similar issues occur.
Q2: Does isError: true always make the client's callTool() throw?
No. A tool execution failure can return an error result in a normal MCP response. Clients need to check isError rather than relying only on catch to determine success.
🧪 Exercise
Register get_price in 02.first-server.mjs (replace the existing tool with that name if you completed the previous exercise). Reuse productInputSchema and getProduct() to query prices, define a structured result containing price, and handle missing products and failed API requests.
Restart the MCP server and use the Node.js client to verify that P100 returns CNY 199, P999 returns a tool error, and ABC fails argument validation.
🎉 You can now wrap business APIs as MCP tools and handle argument validation, structured results, and execution exceptions.
