DEV Community

Kasi Yaswanth
Kasi Yaswanth

Posted on

Day 23/30: Expose Tools with MCP

I still remember the frustration when our team's support bot, powered by LangGraph and MCP, couldn't retain context between user interactions. It was as if the bot had a case of conversational amnesia, forcing users to repeat themselves over and over. We later discovered that the issue stemmed from our lack of a centralized tooling server, making it impossible for the bot to access and leverage external tools in a scalable manner. This experience taught us the importance of building a robust MCP server to expose tools to our AI applications.

In this post, we'll walk through the process of setting up an MCP server, focusing on exposing a single tool to any MCP-compatible AI app. Let's consider a simple tool that performs sentiment analysis on text input. We want this tool to be accessible from our support bot, allowing it to gauge user sentiment and respond accordingly.

The first step in building an MCP server is to define the tool and its interface. MCP provides a set of APIs and protocols for tool definition, including the Tool class and the MCPTool interface. We'll use these to create our sentiment analysis tool. Here's a simplified example of how we might define this tool in Python:

from MCP import Tool, MCPTool

class SentimentAnalysisTool(Tool, MCPTool):
    def __init__(self):
        super().__init__()
        self.name = "SentimentAnalysis"
        self.description = "Analyzes the sentiment of the input text"

    def execute(self, input_text):
        # Simplified sentiment analysis logic for demonstration
        if "love" in input_text or "great" in input_text:
            return "Positive"
        elif "hate" in input_text or "bad" in input_text:
            return "Negative"
        else:
            return "Neutral"

# Create an instance of our tool
sentiment_tool = SentimentAnalysisTool()
Enter fullscreen mode Exit fullscreen mode

Next, we need to set up an MCP server to host our tool. MCP servers can be configured to expose tools over various interfaces, including REST and gRPC. For simplicity, let's use a basic REST server. We'll use Flask, a lightweight Python web framework, to create our server. Here's how we might set it up:

from flask import Flask, request, jsonify
from MCP import ToolServer

app = Flask(__name__)

# Create an MCP tool server
tool_server = ToolServer()

# Register our sentiment analysis tool with the server
tool_server.register_tool(sentiment_tool)

# Define a route for tool execution
@app.route('/tools/<tool_name>/execute', methods=['POST'])
def execute_tool(tool_name):
    tool = tool_server.get_tool(tool_name)
    if tool:
        input_text = request.json['input_text']
        result = tool.execute(input_text)
        return jsonify({'result': result})
    else:
        return jsonify({'error': 'Tool not found'}), 404

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

With our MCP server up and running, our support bot (or any other MCP-compatible AI app) can now access the sentiment analysis tool by sending a POST request to the /tools/SentimentAnalysis/execute endpoint with the text to be analyzed in the request body.

A practical gotcha to watch out for when building MCP servers is ensuring that tool registration and server configuration are properly synchronized. If tools are registered after the server has started, they might not be accessible until the server is restarted. To avoid this, consider implementing a dynamic tool registration mechanism that updates the server's tool list in real-time.

As we move forward in our agentic AI journey, tomorrow we'll explore more advanced topics in integrating LangGraph and MCP, further enhancing our AI applications' capabilities.

Top comments (0)