AI Workflows

How to Build an MCP Server in TypeScript

Learn step-by-step how to build an MCP server using TypeScript, access APIs like Open Library, and debug with MCP Inspector.

5 min read

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

  1. Initialize a TypeScript Project:

    • Start by creating a new directory for your project.
    bash
    mkdir mcp-server
    cd mcp-server
    npm init -y
    • Install required dependencies:
    bash
    npm install mcp-sdk @types/node typescript ts-node
  2. Set Up TypeScript Configuration: Generate a tsconfig.json file:

    bash
    npx tsc --init

    Modify tsconfig.json:

    json
    {
      "compilerOptions": {
        "target": "ES2020",
        "module": "commonjs",
        "outDir": "./dist",
        "strict": true,
        "esModuleInterop": true
      }
    }
  3. Create Entry Files:

    • Set up the src directory:
    bash
    mkdir src
    touch src/index.ts
    • In src/index.ts:
    typescript
    import { 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.");
  4. Run and Test the Server: Use npm scripts to run the server:

    bash
    npx ts-node src/index.ts
  5. Customize for Open Library API: Replace the content of helloWorldTool with a tool to interact with Open Library:

    typescript
    import 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);
  6. Test with MCP Inspector: Run MCP Inspector to debug and validate the server functionality:

    bash
    npx mcp-inspector
    • Follow the prompts to connect MCP Inspector to your running server.
    • Use MCP Inspector to call the search_books tool 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:

typescript
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

  1. Start your server using:
    bash
    npx ts-node src/index.ts
  2. Launch MCP Inspector with:
    bash
    npx mcp-inspector
  3. Connect MCP Inspector to your running server by specifying the command as node dist/index.js (adjust path if needed).
  4. List the tools available by running the list command in the simple inspector.
  5. Use input parameters like query, limit, and page to verify the output of your search_books tool.

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.