# Understanding the xiaohongshu-mcp System Architecture: A Technical Deep Dive

> Explore the xiaohongshu-mcp system architecture. This Go microservice uses headless Chrome automation to bridge HTTP and MCP requests, detailing its four-layer pipeline from CLI to web UI.

- Repository: [zy/xiaohongshu-mcp](https://github.com/xpzouying/xiaohongshu-mcp)
- Tags: deep-dive
- Published: 2026-03-09

---

**The xiaohongshu-mcp system is a Go-based microservice that bridges HTTP and MCP requests to the Xiaohongshu (Little Red Book) creator platform using headless Chrome automation via go-rod, implementing a four-layer pipeline from CLI entry to web UI manipulation.**

The `xpzouying/xiaohongshu-mcp` repository provides an open-source automation bridge that enables programmatic content publishing and interaction with Xiaohongshu through both RESTful APIs and the Model Context Protocol (MCP). This architecture abstracts complex web UI interactions into reusable service methods, handling authentication, media processing, and browser automation in a headless environment.

## Four-Layer Architecture

The system is organized into distinct logical layers that separate concerns from runtime configuration down to specific web automation actions.

### Entry and Runtime Layer

The **Entry and Runtime Layer** handles command-line interface (CLI) parsing, headless mode configuration, and server bootstrap. Located in [`main/main.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/main.go), this layer initializes the global configuration through `configs.InitHeadless` and `configs.SetBinPath`, parsing flags such as `-headless` and `-bin` to determine the Chrome binary path and execution mode. This layer is responsible for booting the HTTP server on the specified port (default `:18060`).

### Application Server Layer

The **Application Server Layer** orchestrates the service lifecycle and protocol handlers. Implemented in [`main/app_server.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/app_server.go), the `AppServer` struct holds the singleton `XiaohongshuService` instance and initializes the MCP server via `InitMCPServer`. This layer binds the business logic to both HTTP and MCP transports, starting the Gin-based HTTP listener and registering the service methods as remote procedure calls.

### Routing and API Layer

The **Routing and API Layer** maps incoming HTTP requests to handler functions. Defined in [`main/routes.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/routes.go) and [`main/handlers_api.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/handlers_api.go), this layer uses the Gin framework to route REST endpoints under `/api/v1/` to specific handlers like `appServer.publishHandler`. Each handler unmarshals JSON payloads into request structs (e.g., `service.PublishRequest`) and delegates execution to the `XiaohongshuService` methods, returning standardized JSON responses.

### Business Logic Layer

The **Business Logic Layer** encapsulates all Xiaohongshu-specific automation workflows. Centered in [`main/service.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/service.go) and the `main/xiaohongshu/*` package, the `XiaohongshuService` struct provides methods for login (`LoginQRCode`), publishing (`PublishContent`, `PublishVideoContent`), feed retrieval (`GetFeeds`), and social interactions (`CommentFeed`, `LikeFeed`). Each service method creates a fresh Rod browser instance via `newBrowser()` and drives the UI through action structs like `PublishAction` in [`main/xiaohongshu/publish.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/xiaohongshu/publish.go) and [`main/xiaohongshu/publish_video.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/xiaohongshu/publish_video.go).

### Support Utilities

Support utilities provide cross-cutting concerns including:

- **Browser abstraction** ([`main/browser/browser.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/browser/browser.go)): Wraps `headless_browser.Browser` to create configured Rod instances with headless settings.
- **Cookie persistence** ([`main/cookies/cookies.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/cookies/cookies.go)): Implements `saveCookies` and `cookies.NewLoadCookie` to maintain login sessions across browser restarts.
- **Media processing** ([`main/pkg/downloader/images.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/pkg/downloader/images.go)): Downloads remote images via `downloader.NewImageProcessor` before local upload.
- **Text utilities** ([`main/pkg/xhsutil/title.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/pkg/xhsutil/title.go)): Calculates Chinese character length for title validation.

## Request Processing Flow

A typical publishing request flows through eight distinct stages:

1. An **HTTP request** hits `/api/v1/publish` handled by Gin in [`main/routes.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/routes.go).
2. The route forwards to `appServer.publishHandler` in [`main/handlers_api.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/handlers_api.go).
3. The handler unmarshals JSON into `service.PublishRequest` and calls `XiaohongshuService.PublishContent`.
4. `PublishContent` validates input, downloads remote images via `processImages` using `downloader.NewImageProcessor`, and builds a `PublishImageContent` struct.
5. The method invokes `publishContent`, which creates a fresh Rod browser via `newBrowser()` calling `browser.NewBrowser`, and instantiates a `PublishAction` via `xiaohongshu.NewPublishImageAction`.
6. `PublishAction.Publish` drives the UI: uploading images, filling title/content fields, setting tags, schedule, visibility settings, and clicking the publish button.
7. Session state persists through `saveCookies` and `cookies.NewLoadCookie` to maintain authentication.
8. The service returns a `PublishResponse` JSON that the HTTP handler writes to the client.

## MCP Protocol Integration

Beyond REST, the system exposes an **MCP endpoint** at `/mcp` following the Model Context Protocol specification. The `InitMCPServer` function in [`mcp_server.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/mcp_server.go) registers the same `XiaohongshuService` methods as streamable RPC calls using the official SDK (`github.com/modelcontextprotocol/go-sdk/mcp`). This allows AI assistants and MCP-compatible clients to invoke publishing and retrieval operations directly through the protocol, with the server attached to the Gin router in `setupRoutes`.

## Configuration Management

Global configuration resides in the `main/configs` package, storing headless mode flags, browser binary paths, and cached usernames. The system supports environment variable `ROD_BROWSER_BIN` for specifying the Chrome executable when the `-bin` CLI flag is omitted. Username persistence after login is managed through `configs.Username`, enabling session continuity across service restarts.

## Implementation Examples

### Starting the Server

```bash

# Build and run with headless mode on port 18060

go run ./main/main.go -headless=true -port=:18060

```

The binary automatically reads `ROD_BROWSER_BIN` from the environment if `-bin` is not specified.

### Publishing Image Content

```bash
curl -X POST http://localhost:18060/api/v1/publish \
     -H "Content-Type: application/json" \
     -d '{
           "title":"我的春游",
           "content":"今天去郊外踏青，风景超赞！",
           "images":["/path/to/local1.jpg","https://example.com/remote2.png"],
           "tags":["#春天","#郊游"],
           "visibility":"仅自己可见"
         }'

```

### MCP Client Integration

```go
import (
    "context"
    "github.com/modelcontextprotocol/go-sdk/mcp"
)

func main() {
    client := mcp.NewClient("http://localhost:18060/mcp")
    resp, err := client.Call(context.Background(), "PublishContent", map[string]any{
        "title":   "MCP 示例",
        "content": "通过 MCP 调用发布",
        "images":  []string{"/tmp/img.jpg"},
    })
    // resp contains the PublishResponse JSON
}

```

## Summary

- **xpzouying/xiaohongshu-mcp** implements a four-layer architecture separating runtime, server orchestration, routing, and business logic concerns.
- The system uses **go-rod** to automate headless Chrome interactions with the Xiaohongshu web UI, creating fresh browser instances per operation in [`main/service.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/service.go).
- **Dual protocol support** enables both RESTful HTTP APIs at `/api/v1/` and MCP protocol access at `/mcp` for AI tool integration.
- **Cookie persistence** in [`main/cookies/cookies.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/cookies/cookies.go) maintains login sessions across requests, while [`main/pkg/downloader/images.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/pkg/downloader/images.go) handles remote media preprocessing.
- All core automation logic resides in [`main/service.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/service.go) and the `main/xiaohongshu/*` package, providing methods for publishing, feed retrieval, and social interactions.

## Frequently Asked Questions

### How does xiaohongshu-mcp handle browser automation?

The system utilizes the **go-rod** library to control a headless Chrome instance. Each service method in [`main/service.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/service.go) creates a fresh browser via `browser.NewBrowser` defined in [`main/browser/browser.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/browser/browser.go), ensuring isolation between requests. The automation scripts in [`main/xiaohongshu/publish.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/xiaohongshu/publish.go) navigate to specific URLs, locate DOM elements, and simulate user interactions like clicking buttons and filling forms.

### What is the difference between the HTTP and MCP interfaces?

The **HTTP interface** provides traditional REST endpoints under `/api/v1/` handled by Gin handlers in [`main/handlers_api.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/handlers_api.go), returning JSON responses. The **MCP interface** exposes the same `XiaohongshuService` methods through the Model Context Protocol at `/mcp`, allowing AI assistants to discover and invoke tools via the `github.com/modelcontextprotocol/go-sdk/mcp` SDK. Both interfaces ultimately execute identical business logic in [`main/service.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/service.go).

### How does the system maintain login sessions between requests?

Login persistence is managed through the [`main/cookies/cookies.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/cookies/cookies.go) package, which implements `saveCookies` to serialize authentication data to disk and `cookies.NewLoadCookie` to hydrate new browser instances with previous session state. After successful QR-code authentication via [`main/xiaohongshu/login.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/xiaohongshu/login.go), the username is cached in `configs.Username` for subsequent validation without re-authentication.

### Can xiaohongshu-mcp handle both local and remote media files?

Yes. The `processImages` method in [`main/service.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/service.go) utilizes `downloader.NewImageProcessor` from [`main/pkg/downloader/images.go`](https://github.com/xpzouying/xiaohongshu-mcp/blob/main/main/pkg/downloader/images.go) to fetch remote images via HTTP before processing. Local file paths are passed directly to the upload automation, while remote URLs are downloaded to temporary storage, ensuring the Xiaohongshu web interface receives valid file inputs regardless of the source.