From Zero to MCP: Building a Model Context Protocol Server with TypeScript and the Star Wars API

If you’re not familiar with Model Context Protocol (MCP) yet, you’re missing out on one of the most promising technologies for integrating AI with external data and tools. And if you’re a Star Wars fan, this live stream will be even more special! 🌟

I …


This content originally appeared on DEV Community and was authored by Glaucia Lemos

If you're not familiar with Model Context Protocol (MCP) yet, you're missing out on one of the most promising technologies for integrating AI with external data and tools. And if you're a Star Wars fan, this live stream will be even more special! 🌟

I recently did a complete live stream where I explained from theoretical fundamentals to practical implementation of an MCP server that connects Claude Desktop with the public Star Wars API (SWAPI). In this article, I'll summarize the main topics covered and give you a complete roadmap to start your journey with MCP.

🎥 Watch the Complete Live Stream

Before we dive into the content, I invite you to watch the complete live stream on YouTube, where I demonstrate step by step the entire creation process:

  • ▶️ Watch the Live Stream: From Zero to MCP with TypeScript

💡 The live stream is available with chapters to facilitate navigation between topics!

📚 What is Model Context Protocol (MCP)?

MCP is a revolutionary protocol that allows language models (LLMs) to access external data and tools in a secure and standardized way. Think of it as a bridge between the AI model and the real world.

Why is MCP important?

Instead of giving direct access to the internet or your data, MCP acts as a controlled translator:

  1. User asks a question in the MCP Client (e.g., Claude Desktop)
  2. MCP Client interprets and sends to MCP Server
  3. MCP Server executes the action (HTTP call to API)
  4. API processes and returns data
  5. MCP Server formats the response
  6. AI Model receives and presents to the user

All of this happens via stdio (standard input and output), without the model directly accessing the internet.

🏗️ Project Architecture

The project we created during the live stream is intentionally simple to facilitate learning:

swapi-mcp-server-app/
├── src/
│   ├── index.ts          # MCP Server + Tools Logic
│   └── types.ts          # TypeScript Interfaces (People, Planets, Films)
├── build/                # Compiled JS files
├── package.json          # Dependencies and scripts
├── tsconfig.json         # TypeScript configuration
└── claude_desktop_config.json  # MCP Client configuration

Technologies Used

  • Node.js - JavaScript Runtime
  • TypeScript - Static typing and safety
  • MCP SDK (@modelcontextprotocol/sdk) - Official MCP SDK
  • Axios - HTTP client for API calls
  • Zod - Schema and type validation
  • SWAPI - Star Wars API (public API)
  • Claude Desktop - To be used as MCP Client

🔧 Implemented Features

Tools (Actions)

We created 4 tools that the model can execute:

  1. search_characters - Search characters by name

    • Example: "Search for information about Luke Skywalker"
  2. search_planets - Search planets by name

    • Example: "Find data about Tatooine"
  3. search_films - Search films by title

    • Example: "Search for the film A New Hope"
  4. get_character_by_id - Get character by ID

    • Example: "Get the character with ID 4"

Resources (Data)

We implemented 1 resource for direct data access:

  • all_films - List all films ordered by episode

💻 Step-by-Step Implementation

1. Initial Setup

First, we create the project and install dependencies:

npm init -y
npm install @modelcontextprotocol/sdk axios zod
npm install --save-dev @types/node typescript

2. Configuring package.json

We configure essential scripts and the bin to make the server executable:

{
  "name": "swapi-mcp-server-app",
  "type": "module",
  "bin": {
    "swapi-mcp-server": "./build/index.js"
  },
  "scripts": {
    "build": "tsc",
    "watch": "tsc --watch",
    "inspector": "npx @modelcontextprotocol/inspector build/index.js"
  }
}

💡 Tip: The inspector script is ESSENTIAL for testing your MCP before integrating it with Claude Desktop!

3. Defining Types (types.ts)

We create TypeScript interfaces based on SWAPI documentation:

export interface People {
  name: string;
  height: string;
  mass: string;
  hair_color: string;
  eye_color: string;
  birth_year: string;
  gender: string;
  homeworld: string;
  films: string[];
  // ... other properties
}

export interface SearchResponse<T> {
  count: number;
  next: string | null;
  previous: string | null;
  results: T[];
}

The SearchResponse<T> is generic and can be reused for different data types.

4. Creating the MCP Server (index.ts)

4.1 Instantiating the Server

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

class SwapiMcpServer {
  private server: McpServer;
  private axiosInstance;

  constructor() {
    this.server = new McpServer({
      name: "swapi-mcp-server",
      version: "1.0.0",
    });

    this.axiosInstance = axios.create({
      baseURL: "https://swapi.dev/api",
      timeout: 10000,
    });

    this.setupTools();
    this.setupResources();
  }
}

4.2 Registering a Tool

private setupTools(): void {
  this.server.registerTool(
    "search_characters",
    {
      title: "Search Characters",
      description: "Search Star Wars characters by name",
      inputSchema: {
        search: z.string().describe("Character name to search"),
      },
    },
    async ({ search }) => {
      try {
        const response = await this.axiosInstance.get<SearchResponse<People>>(
          "/people/",
          { params: { search } }
        );

        if (response.data.results.length === 0) {
          return {
            content: [{
              type: "text" as const,
              text: `No characters found with the name "${search}".`,
            }],
          };
        }

        const charactersInfo = response.data.results
          .map((char) => `Name: ${char.name}\nHeight: ${char.height}cm\n...`)
          .join("\n---\n\n");

        return {
          content: [{
            type: "text" as const,
            text: `Found ${response.data.results.length} character(s):\n\n${charactersInfo}`,
          }],
        };
      } catch (error) {
        return this.handleError(error, "search characters");
      }
    }
  );
}

4.3 Connecting via Stdio

async run(): Promise<void> {
  const transport = new StdioServerTransport();
  await this.server.connect(transport);
  console.error("SWAPI MCP Server running on stdio");
}

const server = new SwapiMcpServer();
server.run().catch((error) => {
  console.error("Fatal error starting server:", error);
  process.exit(1);
});

🧪 Testing with MCP Inspector

Before integrating with Claude Desktop, ALWAYS test with Inspector:

npm run build
npm run inspector

The Inspector opens a web interface where you can:

  • ✅ List all available tools
  • ✅ Test each tool individually
  • ✅ View and test created resources
  • ✅ Debug connection issues
  • ✅ See logs in real-time

Test example:

  1. Click on "Connect"
  2. Go to "Tools" → "search_characters"
  3. Type "Darth Vader" in the search field
  4. Click on "Run Tool"
  5. See the formatted response!

🔌 Connecting to Claude Desktop

1. Locate the configuration file

On Windows:

%APPDATA%\Claude\claude_desktop_config.json

2. Add the MCP Server configuration

{
  "mcpServers": {
    "swapi-mcp-server": {
      "command": "node",
      "args": [
        "C:/Users/YOUR_USER/path/to/swapi-mcp-server-app/build/index.js"
      ]
    }
  }
}

⚠️ IMPORTANT: Use the absolute path to the build/index.js file!

3. Restart Claude Desktop

Close completely and reopen Claude Desktop.

4. Test with natural questions

Now you can ask questions like:

  • "Search for information about Luke Skywalker"
  • "Find data about the planet Tatooine"
  • "List all Star Wars films"
  • "What is the character with ID 4?"

Claude will automatically identify which tool to use and call your MCP Server! 🎉

🎯 Main Takeaways from the Live Stream

1. MCP vs Direct Internet Access

MCP offers:

  • Granular control over what the AI can access
  • Security - no direct access to sensitive data
  • Standardization - same protocol for different sources
  • Validation - Zod ensures correct types (TypeScript)

2. Tools vs Resources

Aspect Tools Resources
Purpose Dynamic actions Ready data
Input Requires user parameters No input
Example Search character by name List all films
Registration server.registerTool() server.registerResource()

3. Best Practices

DON'T:

  • Leave API URLs exposed in code (use .env)
  • Forget to validate inputs with Zod
  • Skip testing with Inspector

DO:

  • Use environment variables for sensitive data
  • Validate all inputs
  • Test exhaustively before integrating
  • Document your tools clearly

🌟 Infinite Possibilities

What we created during the live stream is just the beginning! Imagine applying MCP to:

Business Use Cases

  • 🏢 Corporate API - Standardize PRs on GitHub
  • 📊 Analytics Dashboard - Query real-time metrics
  • 🗄️ Database - Natural queries in SQL
  • 📁 Internal Documentation - Semantic search

Next Steps

  1. ✅ Add more SWAPI types (vehicles, species, starships)
  2. ✅ Implement caching with Redis
  3. ✅ Add authentication for private APIs
  4. ✅ Deploy to production (Azure, AWS, etc.)
  5. ✅ Create automated tests

📦 Repository and Resources

All the code from the live stream is available on GitHub:

  • 📂 Repository: swapi-mcp-server-app

GitHub logo glaucia86 / swapi-mcp-server-app

An application for study purposes to understand more about MCP with TypeScript using Star Wars API

🌟 Star Wars MCP Server

TypeScript Node.js MCP Star Wars API Claude Desktop

Um servidor MCP (Model Context Protocol) que fornece acesso à Star Wars API (SWAPI) através do Claude Desktop

📖 Sobre o Projeto

Este projeto é um servidor MCP desenvolvido em TypeScript que integra a Star Wars API (SWAPI) com o Claude Desktop. Ele permite que você faça perguntas sobre o universo Star Wars e obtenha informações detalhadas sobre personagens, planetas, filmes e muito mais, diretamente através do Claude.

✨ Funcionalidades

🔧 Tools Disponíveis

  • search_characters - Busca personagens do Star Wars por nome
  • search_planets - Busca planetas do Star Wars por nome
  • search_films - Busca filmes do Star Wars por título
  • get_character_by_id - Obtém informações detalhadas de um personagem pelo ID

📚 Resources Disponíveis

  • all_films - Lista todos os filmes da saga Star Wars ordenados por episódio

🚀 Como Executar

Pré-requisitos

  • Node.js (versão 18 ou superior)
  • Claude Desktop instalado
  • npm ou yarn

1. Instalação

# Clone

What you'll find in the repository:

  • ✅ Complete and commented code
  • ✅ Detailed README with instructions
  • ✅ Example questions to test
  • ✅ Troubleshooting common issues
  • ✅ Structure ready to expand
  • ✅ And detailed explanation of the theoretical part given during the live stream

⭐ Don't forget to star the repository!

🎓 Additional Resources

Official Documentation

Upcoming Live Streams

I'm already planning a Zero to Hero series on LangChain.js! There will be approximately 23 videos covering from basics to advanced topics including: LangGraph and LangSmith.

📺 Subscribe to the channel so you don't miss it:

YouTube: @glaucialemos

🤔 Frequently Asked Questions

1. Does MCP only work with Claude Desktop?

No! You can use MCP with:

  • Claude Desktop ✅
  • Visual Studio Code (with extensions) ✅
  • Cursor ✅
  • Any client that implements the MCP protocol

2. Do I need to pay to use Claude Desktop?

No! Claude Desktop is free and you can use MCPs locally at no cost.

3. How do I deploy an MCP Server?

For production, you'll need to:

  • Host the server (Azure, AWS, etc.)
  • Configure environment variables
  • Implement authentication
  • Use Docker for containerization

(I'm still studying the best approach - I'll do a live stream about this soon!)

4. Does MCP replace REST APIs?

No! MCP complements REST APIs, providing an abstraction layer that allows AI models to interact with them in a standardized way.

💬 Let's Talk!

Did you enjoy the content? Have questions or suggestions? Find me on social media:

🎬 Call to Action

  1. ▶️ Watch the complete live stream on YouTube
  2. ⭐ Star the repository
  3. 💬 Leave your questions in the comments
  4. 🔔 Subscribe to the channel for the LangChain.js series

🌌 Conclusion

Model Context Protocol is revolutionizing the way we integrate AI with external systems. With just a few hundred lines of TypeScript code, we created a server that allows Claude Desktop to access all the richness of Star Wars universe data in a secure and controlled way.

Now it's your turn! Take the code, adapt it to your favorite API, and explore the infinite possibilities of MCP.

May the Force (and the Code) be with you! ⭐✨


This content originally appeared on DEV Community and was authored by Glaucia Lemos


Print Share Comment Cite Upload Translate Updates
APA

Glaucia Lemos | Sciencx (2025-10-21T14:18:32+00:00) From Zero to MCP: Building a Model Context Protocol Server with TypeScript and the Star Wars API. Retrieved from https://www.scien.cx/2025/10/21/from-zero-to-mcp-building-a-model-context-protocol-server-with-typescript-and-the-star-wars-api/

MLA
" » From Zero to MCP: Building a Model Context Protocol Server with TypeScript and the Star Wars API." Glaucia Lemos | Sciencx - Tuesday October 21, 2025, https://www.scien.cx/2025/10/21/from-zero-to-mcp-building-a-model-context-protocol-server-with-typescript-and-the-star-wars-api/
HARVARD
Glaucia Lemos | Sciencx Tuesday October 21, 2025 » From Zero to MCP: Building a Model Context Protocol Server with TypeScript and the Star Wars API., viewed ,<https://www.scien.cx/2025/10/21/from-zero-to-mcp-building-a-model-context-protocol-server-with-typescript-and-the-star-wars-api/>
VANCOUVER
Glaucia Lemos | Sciencx - » From Zero to MCP: Building a Model Context Protocol Server with TypeScript and the Star Wars API. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/10/21/from-zero-to-mcp-building-a-model-context-protocol-server-with-typescript-and-the-star-wars-api/
CHICAGO
" » From Zero to MCP: Building a Model Context Protocol Server with TypeScript and the Star Wars API." Glaucia Lemos | Sciencx - Accessed . https://www.scien.cx/2025/10/21/from-zero-to-mcp-building-a-model-context-protocol-server-with-typescript-and-the-star-wars-api/
IEEE
" » From Zero to MCP: Building a Model Context Protocol Server with TypeScript and the Star Wars API." Glaucia Lemos | Sciencx [Online]. Available: https://www.scien.cx/2025/10/21/from-zero-to-mcp-building-a-model-context-protocol-server-with-typescript-and-the-star-wars-api/. [Accessed: ]
rf:citation
» From Zero to MCP: Building a Model Context Protocol Server with TypeScript and the Star Wars API | Glaucia Lemos | Sciencx | https://www.scien.cx/2025/10/21/from-zero-to-mcp-building-a-model-context-protocol-server-with-typescript-and-the-star-wars-api/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.