Learn step-by-step how to build an MCP (Model Context Protocol) server using TypeScript. This guide will help you create a server that interacts with the Open Library API, allowing seamless integration with Language Models via the MCP ecosystem.
Prerequisites for Building an MCP Server
Before you start building an MCP server in TypeScript, ensure you have the following:
prerequisites
- Node.js: Installed on your system, version 18 or higher.
- npm (Node Package Manager): Comes with Node.js.
- Visual Studio Code (VS Code): A popular code editor.
- MCP TypeScript SDK: Installable through npm.
- Familiarity with Open Library API documentation: To understand the API endpoints and parameters.
- MCP Inspector: For testing and debugging your MCP server; ensure this is installed or available.
- Basic knowledge of TypeScript: Understanding TypeScript syntax and basic concepts is essential.
Steps to Create the MCP Server
Follow these steps to build an MCP server using TypeScript:
steps
Initialize a TypeScript Project:
- Start by creating a new directory for your project.
bashmkdir mcp-server cd mcp-server npm init -y- Install required dependencies:
bashnpm install mcp-sdk @types/node typescript ts-nodeSet Up TypeScript Configuration: Generate a
tsconfig.jsonfile:bashnpx tsc --initModify
tsconfig.json:json{ "compilerOptions": { "target": "ES2020", "module": "commonjs", "outDir": "./dist", "strict": true, "esModuleInterop": true } }Create Entry Files:
- Set up the
srcdirectory:
bashmkdir src touch src/index.ts- In
src/index.ts:
typescriptimport { createServer, Tool } from "mcp-sdk"; const server = createServer(); const helloWorldTool: Tool = { name: "hello_world", description: "A simple Hello World tool", inputParameters: { name: { type: "string", description: "Your name" } }, async execute({ name }) { return { greeting: `Hello World, ${name}!` }; }, }; server.addTool(helloWorldTool); server.start(); console.log("MCP server started.");- Set up the
Run and Test the Server: Use npm scripts to run the server:
bashnpx ts-node src/index.tsCustomize for Open Library API: Replace the content of
helloWorldToolwith a tool to interact with Open Library:typescriptimport fetch from "node-fetch"; const searchBooksTool: Tool = { name: "search_books", description: "Search books using Open Library API", inputParameters: { query: { type: "string", description: "Search keywords" }, limit: { type: "number", description: "Number of results", optional: true }, page: { type: "number", description: "Page number", optional: true }, }, async execute({ query, limit = 10, page = 1 }) { const response = await fetch( `https://openlibrary.org/search.json?q=${encodeURIComponent(query)}&limit=${limit}&page=${page}` ); const data = await response.json(); return data.docs .slice(0, limit) .map((book: any) => ({ title: book.title, author: book.author_name?.join(", "), year: book.first_publish_year, })); }, }; server.addTool(searchBooksTool);Test with MCP Inspector: Run MCP Inspector to debug and validate the server functionality:
bashnpx mcp-inspector- Follow the prompts to connect MCP Inspector to your running server.
- Use MCP Inspector to call the
search_bookstool and verify the results.
Example Code for MCP Server with Open Library API
Below is an example of a complete MCP server implementation with the Open Library API:
import fetch from "node-fetch";
import { createServer, Tool } from "mcp-sdk";
const server = createServer();
const searchBooksTool: Tool = {
name: "search_books",
description: "Search books using Open Library API",
inputParameters: {
query: { type: "string", description: "Search keywords" },
limit: { type: "number", description: "Number of results", optional: true },
page: { type: "number", description: "Page number", optional: true },
},
async execute({ query, limit = 10, page = 1 }) {
const response = await fetch(
`https://openlibrary.org/search.json?q=${encodeURIComponent(query)}&limit=${limit}&page=${page}`
);
const data = await response.json();
return data.docs
.slice(0, limit)
.map((book: any) => ({
title: book.title,
author: book.author_name?.join(", "),
year: book.first_publish_year,
}));
},
};
server.addTool(searchBooksTool);
server.start();
console.log("MCP server started successfully.");Run the server and test it using the MCP Inspector to ensure proper functionality.
Common Issues and Debugging
Testing and Verification Using MCP Inspector
Testing your MCP server with the MCP Inspector ensures proper implementation. Follow these steps:
steps
- Start your server using:bash
npx ts-node src/index.ts - Launch MCP Inspector with:bash
npx mcp-inspector - Connect MCP Inspector to your running server by specifying the command as
node dist/index.js(adjust path if needed). - List the tools available by running the
listcommand in the simple inspector. - Use input parameters like
query,limit, andpageto verify the output of yoursearch_bookstool.
Final Thoughts on Building MCP Servers
FAQ
How can I handle rate limiting with the Open Library API?
The Open Library API has rate limits in place. To handle this, consider implementing a retry mechanism with exponential backoff to wait if you encounter rate-limiting errors.
Can I use another API with the MCP TypeScript server?
Yes, the MCP SDK is highly flexible and can work with any API. You’ll need to adapt the tool logic to perform API requests and handle responses accordingly.
How can I deploy my MCP server to production?
You can deploy your MCP server using platforms such as AWS, Heroku, or similar service providers. Package and deploy the dist/ folder containing the compiled JavaScript output of your TypeScript project.
Official reference: Model Context Protocol documentation.