In this guide, we will go through various flows and show you the fastest and easiest way to get started with building a Kafka MCP Server.
The Model Context Protocol (MCP) is an open protocol that enables secure connections between host applications (like Claude Desktop) and external data sources and tools. MCP allows AI assistants to:
- Access real-time data from external systems
- Execute operations on behalf of users
- Provide contextual information from various sources
Learn more about MCP Protocol.
- How to set up a Kafka development environment using Docker
- How to build an MCP server using FastMCP framework
- How to implement Kafka operations as MCP tools (connect, list topics, create/delete topics, produce messages)
- How to integrate your MCP server with Claude Desktop
- A complete MCP server that provides Kafka operations as tools for AI assistants
- Integration with Claude Desktop for natural language Kafka operations
- Python 3.10 or higher
- Docker and Docker Compose
- A code editor (VS Code recommended)
- Basic understanding of Python and Kafka concepts
In a new terminal, run the following statements to set up your environment. This will:
- Clone the repository and navigate to the project directory
- Create a Python virtual environment
- Install required dependencies
# Clone the repository
git clone https://github.com/Daminivenkateswaralu/kafka-mcp.git
cd kafka-mcp
# Create Python virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt- Open the docker application
# Start Kafka using Docker Compose
docker compose up -d
# Verify Kafka is running
docker compose psThis will start a single Kafka broker accessible at localhost:9092.
Important: If you use different configuration, be sure to update the kafka.properties file accordingly.
Let's start by setting up the basic MCP server structure. We'll use the skeleton file server_skeleton.py as our starting point.
First, uncomment and update the import statement in your server_skeleton.py:
# TODO: Import kafka utilities
from kafka_utils import KafkaManagerAdd the following code to initialize the MCP server. Replace the TODO comment:
# TODO: Initialize the MCP server
mcp = FastMCP("Kafka MCP Server", lifespan=kafka_lifespan)In the kafka_lifespan function, add proper cleanup code:
@asynccontextmanager
async def kafka_lifespan(server: FastMCP) -> AsyncIterator[KafkaContext]:
"""Manage Kafka connections lifecycle"""
context = KafkaContext()
try:
logger.info("Starting Kafka MCP Server...")
yield context
finally:
logger.info("Shutting down Kafka MCP Server...")
# TODO: Add cleanup code here
if context.kafka_manager:
context.kafka_manager.close()Update the main section at the bottom of the file:
if __name__ == "__main__":
# TODO: Run the server
logger.info("Starting Kafka MCP Server...")
mcp.run()Now let's implement the connection functionality using the FastMCP framework.
Replace the # TODO: Implement kafka_initialize_connection tool comment with:
@mcp.tool()
def kafka_initialize_connection(config_file: str, ctx: Context) -> str:
"""Connect to Kafka using a properties file"""
try:
kafka_manager = KafkaManager(config_file)
# Store in the lifespan context
ctx.request_context.lifespan_context.kafka_manager = kafka_manager
return f"Successfully connected to Kafka using config file: {config_file}"
except Exception as e:
return f"Failed to connect to Kafka: {str(e)}"Run the MCP server in development mode:
mcp dev server_skeleton.py- Open the MCP Inspector site in your browser.
- Configure the session token:
- Copy the session token displayed in your terminal after running the server.
- Paste this token into the "Session Token" field in the site's configuration.
- Set up the command to run your server:
- In the "Command" field, enter:
python - In the "Arguments" field, enter:
server_skeleton.py
- In the "Command" field, enter:
This opens the MCP Inspector. Test your connection tool by running:
{
"name": "kafka_initialize_connection",
"arguments": {
"config_file": "kafka.properties"
}
}You should see: "Successfully connected to Kafka using config file: kafka.properties"
Using the FastMCP framework, we'll add the ability to list Kafka topics.
Replace the # TODO: Implement kafka_list_topics tool comment with:
@mcp.tool()
def kafka_list_topics(ctx: Context) -> str:
"""List all topics in the Kafka cluster"""
kafka_manager = ctx.request_context.lifespan_context.kafka_manager
if not kafka_manager:
return "Error: Not connected to Kafka. Please use kafka_initialize_connection first."
try:
topics = kafka_manager.list_topics()
if topics:
topics_info = []
for topic in topics:
topics_info.append(
f"• {topic['name']} (partitions: {topic['partitions']}, replication: {topic['replication_factor']})"
)
return f"Topics in Kafka cluster:\n" + "\n".join(topics_info)
else:
return "No topics found in the Kafka cluster."
except Exception as e:
return f"Error listing topics: {str(e)}"In the MCP Inspector, first connect to Kafka, then list topics:
{
"name": "kafka_list_topics",
"arguments": {}
}Now let's add topic creation functionality.
Replace the # TODO: Implement kafka_create_topic tool comment with:
@mcp.tool()
def kafka_create_topic(
name: str,
partitions: int = 1,
replication_factor: int = 1,
config: Optional[Dict[str, str]] = None,
ctx: Context = None,
) -> str:
"""Create a new Kafka topic"""
kafka_manager = ctx.request_context.lifespan_context.kafka_manager
if not kafka_manager:
return "Error: Not connected to Kafka. Please use kafka_initialize_connection first."
try:
result = kafka_manager.create_topic(
name, partitions, replication_factor, config
)
return json.dumps(result, indent=2)
except Exception as e:
return f"Error creating topic: {str(e)}"Create a test topic:
{
"name": "kafka_create_topic",
"arguments": {
"name": "user-events",
"partitions": 3,
"replication_factor": 1
}
}Then list topics again to verify it was created.
Let's add the ability to delete topics.
Replace the # TODO: Implement kafka_delete_topic tool comment with:
@mcp.tool()
def kafka_delete_topic(name: str, ctx: Context) -> str:
"""Delete a Kafka topic"""
kafka_manager = ctx.request_context.lifespan_context.kafka_manager
if not kafka_manager:
return "Error: Not connected to Kafka. Please use kafka_initialize_connection first."
try:
result = kafka_manager.delete_topic(name)
return json.dumps(result, indent=2)
except Exception as e:
return f"Error deleting topic: {str(e)}"Add detailed topic inspection capability.
Replace the # TODO: Implement kafka_get_topic_info tool comment with:
@mcp.tool()
def kafka_get_topic_info(name: str, ctx: Context) -> str:
"""Get detailed information about a specific topic"""
kafka_manager = ctx.request_context.lifespan_context.kafka_manager
if not kafka_manager:
return "Error: Not connected to Kafka. Please use kafka_initialize_connection first."
try:
result = kafka_manager.get_topic_info(name)
return json.dumps(result, indent=2)
except Exception as e:
return f"Error getting topic info: {str(e)}"Get details about your test topic:
{
"name": "kafka_get_topic_info",
"arguments": {
"name": "user-events"
}
}Finally, let's implement message production.
Replace the # TODO: Implement kafka_send_message tool comment with:
@mcp.tool()
def kafka_send_message(
topic: str,
message: Optional[Any] = None,
key: Optional[str] = None,
ctx: Context = None,
) -> str:
"""Send a message to a Kafka topic"""
if message is None:
return "Error: 'message' must be provided."
kafka_manager = ctx.request_context.lifespan_context.kafka_manager
if not kafka_manager:
return "Error: Not connected to Kafka. Please use kafka_initialize_connection first."
try:
result = kafka_manager.send_message(topic, message, key)
return json.dumps(result, indent=2)
except Exception as e:
return f"Error sending message: {str(e)}"Send a test message:
{
"name": "kafka_send_message",
"arguments": {
"topic": "user-events",
"message": {
"user_id": 123,
"action": "login",
"timestamp": "2024-01-15T10:30:00Z"
},
"key": "user-123"
}
}To connect your MCP server with Claude Desktop, open the settings and update your claude_desktop_config.json file. Add your MCP server configuration under the mcpServers section as shown below:
{
"mcpServers": {
"kafka": {
"command": "/path/to/your/venv/bin/python",
"args": ["/path/to/your/server_skeleton.py"]
}
}
}Try these example interactions with Claude:
-
Connect to Kafka:
"Initialize connection to Kafka using the kafka.properties file" -
List Topics:
"Show me all topics in the Kafka cluster" -
Create a Topic:
"Create a topic called 'orders' with 5 partitions" -
Send Messages:
"Send a message to the orders topic with this data: {'order_id': 'ORD-001', 'amount': 99.99}"
Create these test topics and messages to verify your implementation:
// Basic topic
{
"name": "kafka_create_topic",
"arguments": {
"name": "test-topic",
"partitions": 1,
"replication_factor": 1
}
}
// Topic with custom configuration
{
"name": "kafka_create_topic",
"arguments": {
"name": "orders",
"partitions": 5,
"replication_factor": 1,
"config": {
"retention.ms": "604800000"
}
}
}// User event message
{
"name": "kafka_send_message",
"arguments": {
"topic": "user-events",
"message": {
"user_id": 12345,
"event_type": "login",
"timestamp": "2024-01-15T10:30:00Z",
"ip_address": "192.168.1.100"
}
}
}
// Order message
{
"name": "kafka_send_message",
"arguments": {
"topic": "orders",
"message": {
"order_id": "ORD-2024-001",
"customer_id": 67890,
"items": [
{"product_id": "PROD-123", "quantity": 2, "price": 29.99}
],
"total_amount": 59.98,
"status": "pending"
}
}
}-
Connection Failed:
- Verify Docker Compose is running:
docker compose ps - Check Kafka logs:
docker compose logs kafka - Verify
kafka.propertiesconfiguration
- Verify Docker Compose is running:
-
MCP Inspector Not Working:
- Ensure you're running
mcp dev server_skeleton.pyfrom the correct directory - Check Python virtual environment is activated
- Verify all dependencies are installed
- Ensure you're running
-
Import Errors:
- Make sure
kafka_utils.pyis in the same directory - Verify kafka-python is installed:
pip install kafka-python
- Make sure
-
Tool Execution Errors:
- Always connect to Kafka first using
kafka_initialize_connection - Check server logs for detailed error messages
- Verify Kafka cluster is healthy
- Always connect to Kafka first using
- Use Logging: The server logs provide detailed information about operations
- Test Incrementally: Test each tool individually in the MCP Inspector
Congratulations! You've successfully completed the Kafka MCP Server workshop.
- Built a complete MCP server for Kafka operations
- Implemented core Kafka functionality (connect, list, create, delete, inspect, send)
- Integrated natural language Kafka management with Claude Desktop
- Created a foundation for further Kafka tooling extensions
- Add Consumer Functionality: Implement message consumption tools
- Error Handling: Add more robust error handling and validation
- Security: Add authentication and authorization for production use
- Monitoring: Add health checks and metrics
- Documentation: Create user guides for your specific use cases