HonoHub Logo

HonoHub

Stateful MCP

Create a stateful MCP with @hono/mcp

Imagine you are building a shopping MCP server, where you need to have a state about the current user and their cart. Example tools could be:

  • Add item to cart
  • Remove item from cart
  • Get cart items
  • Get cart total
  • Checkout
  • etc.

For this, you can create a stateful MCP server. This way, you can maintain the state of the cart for each user across multiple requests.

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPTransport } from "@hono/mcp";
import { Hono } from "hono";
import { useAuth } from "@/middleware";

const app = new Hono().use(useAuth());

function createMCPServer(user: User) {
	const mcpServer = new McpServer({
		name: "my-mcp-server",
		version: "1.0.0",
	});

	// ...
    // Add your stateful tools/prompts/resources here
	// ...

	return mcpServer;
}

app.all("/mcp", async (c) => {
	const user = c.get("user");
	const transport = new StreamableHTTPTransport({
		sessionIdGenerator: () => user.id,
	});

	const mcpServer = createMCPServer(user);
	mcpServer.connect(transport);

	return transport.handleRequest(c);
});

export default app;

Characteristics

  • Stores session data, user preferences, or conversation history
  • Maintain connections to databases or external services
  • Track ongoing operations or workflows

Example Use Cases

  • Shopping Cart MCP Server (Obviously)
  • Database Query MCP Server
  • Multi-step Form MCP Server