Building a Chat App with MCP(Model Context Protocol) and Claude in Node js

Building a Chat App with MCP(Model Context Protocol) in Node.js I recently built a simple chat application that lets Claude call external tools using the Model Context Protocol (MCP). Here's how you can build one too. What is MCP? The Model Context Protocol (MCP) is a standardized way for AI models like Claude to interact with external tools. It provides a structured format for: Defining tools the AI can use Sending requests from the AI to tools Returning results back to the AI Project Structure The application has three main parts: Express Server (server.js): Handles web requests and user sessions MCP Client (mcpClient.js): Connects to Claude and the MCP server MCP Server (mcpServer.js): Defines and implements the tools Chat UI Architecture How to Add Tools to Your MCP Server The MCP server is where you define tools that Claude can use. Here's a basic example of how to create a weather tool: // In mcpServer.js import { Server } from "@modelcontextprotocol/sdk/server/index.js"; const server = new Server({ name: "mcp-weather-server", version: "1.0.0" }); // Define a weather tool server.defineTool({ name: "getCurrentWeather", description: "Get the current weather for a location", inputSchema: { type: "object", properties: { location: { type: "string", description: "The city and state, e.g. San Francisco, CA", }, unit: { type: "string", enum: ["celsius", "fahrenheit"], description: "The unit of temperature to use", }, }, required: ["location"], }, handler: async function (args) { const { location, unit = "celsius" } = args; // Here you would typically call a weather API // For demo purposes, we're returning mock data return { location: location, temperature: unit === "celsius" ? 22 : 72, conditions: "Sunny", humidity: "45%", windSpeed: "10 km/h", }; }, }); // Start the server server.start(); Available Tool Types You can create different types of tools for Claude to use: Data Retrieval Tools: Get weather, news, stock prices, etc. Calculation Tools: Perform complex calculations or data analysis Database Tools: Query or update databases API Integration Tools: Connect to external services File Processing Tools: Read, write, or analyze files How the MCP Client Works The MCP client connects Claude to your tools: async processQuery(query) { // Add user message to history this.chatHistory.push({ role: 'user', content: query }); // Send to Claude with tool definitions const response = await this.anthropic.messages.create({ model: "claude-3-5-sonnet-20241022", max_tokens: 1000, messages: this.chatHistory, tools: this.tools, }); // Process the response for (const content of response.content) { if (content.type === "tool_use") { // Claude wants to use a tool const result = await this.mcp.callTool({ name: content.name, arguments: content.input, }); // Send tool result back to Claude this.chatHistory.push({ role: "user", content: JSON.stringify(result.content), }); } } } Setting Up Your Project To build your own MCP chat app: Clone the repository: git clone https://github.com/RajeshRenato/mcp-node Install dependencies: npm install Add your Anthropic API key to a .env file Create your tools in mcpServer.js Start the server: node server.js Example Tools You Can Build Here are some ideas for tools you could add: News Search: Fetch recent news articles on a topic Wikipedia Lookup: Search and summarize Wikipedia content Calendar Integration: Check or create calendar events Language Translation: Translate text between languages Image Generation: Generate images based on text descriptions (using DALL-E or similar) Conclusion The Model Context Protocol opens up exciting possibilities for AI applications. By giving Claude access to external tools, you can build powerful, interactive applications that combine AI with real-time data and functionality. Want to try it yourself? Get the complete code on GitHub. Got questions? Drop them below!

Apr 13, 2025 - 13:16
 0
Building a Chat App with MCP(Model Context Protocol) and Claude in Node js

Building a Chat App with MCP(Model Context Protocol) in Node.js

I recently built a simple chat application that lets Claude call external tools using the Model Context Protocol (MCP). Here's how you can build one too.

What is MCP?

The Model Context Protocol (MCP) is a standardized way for AI models like Claude to interact with external tools. It provides a structured format for:

  • Defining tools the AI can use
  • Sending requests from the AI to tools
  • Returning results back to the AI

Project Structure

The application has three main parts:

  1. Express Server (server.js): Handles web requests and user sessions
  2. MCP Client (mcpClient.js): Connects to Claude and the MCP server
  3. MCP Server (mcpServer.js): Defines and implements the tools

Chat UI

Image description

Architecture

Image description

How to Add Tools to Your MCP Server

The MCP server is where you define tools that Claude can use. Here's a basic example of how to create a weather tool:

// In mcpServer.js
import { Server } from "@modelcontextprotocol/sdk/server/index.js";

const server = new Server({ name: "mcp-weather-server", version: "1.0.0" });

// Define a weather tool
server.defineTool({
  name: "getCurrentWeather",
  description: "Get the current weather for a location",
  inputSchema: {
    type: "object",
    properties: {
      location: {
        type: "string",
        description: "The city and state, e.g. San Francisco, CA",
      },
      unit: {
        type: "string",
        enum: ["celsius", "fahrenheit"],
        description: "The unit of temperature to use",
      },
    },
    required: ["location"],
  },
  handler: async function (args) {
    const { location, unit = "celsius" } = args;

    // Here you would typically call a weather API
    // For demo purposes, we're returning mock data
    return {
      location: location,
      temperature: unit === "celsius" ? 22 : 72,
      conditions: "Sunny",
      humidity: "45%",
      windSpeed: "10 km/h",
    };
  },
});

// Start the server
server.start();

Available Tool Types

You can create different types of tools for Claude to use:

  1. Data Retrieval Tools: Get weather, news, stock prices, etc.
  2. Calculation Tools: Perform complex calculations or data analysis
  3. Database Tools: Query or update databases
  4. API Integration Tools: Connect to external services
  5. File Processing Tools: Read, write, or analyze files

How the MCP Client Works

The MCP client connects Claude to your tools:

async processQuery(query) {
  // Add user message to history
  this.chatHistory.push({ role: 'user', content: query });

  // Send to Claude with tool definitions
  const response = await this.anthropic.messages.create({
    model: "claude-3-5-sonnet-20241022",
    max_tokens: 1000,
    messages: this.chatHistory,
    tools: this.tools,
  });

  // Process the response
  for (const content of response.content) {
    if (content.type === "tool_use") {
      // Claude wants to use a tool
      const result = await this.mcp.callTool({
        name: content.name,
        arguments: content.input,
      });

      // Send tool result back to Claude
      this.chatHistory.push({
        role: "user",
        content: JSON.stringify(result.content),
      });
    }
  }
}

Setting Up Your Project

To build your own MCP chat app:

  1. Clone the repository: git clone https://github.com/RajeshRenato/mcp-node
  2. Install dependencies: npm install
  3. Add your Anthropic API key to a .env file
  4. Create your tools in mcpServer.js
  5. Start the server: node server.js

Example Tools You Can Build

Here are some ideas for tools you could add:

  • News Search: Fetch recent news articles on a topic
  • Wikipedia Lookup: Search and summarize Wikipedia content
  • Calendar Integration: Check or create calendar events
  • Language Translation: Translate text between languages
  • Image Generation: Generate images based on text descriptions (using DALL-E or similar)

Conclusion

The Model Context Protocol opens up exciting possibilities for AI applications. By giving Claude access to external tools, you can build powerful, interactive applications that combine AI with real-time data and functionality.

Want to try it yourself? Get the complete code on GitHub.

Got questions? Drop them below!