DEV Community

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

Posted on

2 1 1 1 1

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();
Enter fullscreen mode Exit fullscreen mode

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),
      });
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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! 🚀

Top comments (2)

Collapse
 
nevodavid profile image
Nevo David •

Impressive work! How can this framework improve user interactions in real-world applications?

Collapse
 
rajeshrenato profile image
RajeshRenato •

Thanks for the kind words!
Model Context Protocol improves real-world interactions with real-time data, personalized responses, reduced hallucinations, complex workflows, and domain-specific insights.
In my tests and personal use cases, I saw a big boost in accuracy—like getting exact weather info instead of guesses.
Happy to explore how it can fit your needs too!

đź‘‹ Kindness is contagious

Show your support for this compelling post and become part of the vibrant DEV Community. All levels of coders can share insights and build collective wisdom.

Even a brief “thank you” can brighten an author’s day. Drop your kudos below!

At DEV, sharing know-how paves the way and strengthens connections. If this article resonated with you, a quick note of thanks goes a long way.

Count me in!