Understanding the xiaohongshu-mcp System Architecture: A Technical Deep Dive
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, 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, 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 and 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 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 and main/xiaohongshu/publish_video.go.
Support Utilities
Support utilities provide cross-cutting concerns including:
- Browser abstraction (
main/browser/browser.go): Wrapsheadless_browser.Browserto create configured Rod instances with headless settings. - Cookie persistence (
main/cookies/cookies.go): ImplementssaveCookiesandcookies.NewLoadCookieto maintain login sessions across browser restarts. - Media processing (
main/pkg/downloader/images.go): Downloads remote images viadownloader.NewImageProcessorbefore local upload. - Text utilities (
main/pkg/xhsutil/title.go): Calculates Chinese character length for title validation.
Request Processing Flow
A typical publishing request flows through eight distinct stages:
- An HTTP request hits
/api/v1/publishhandled by Gin inmain/routes.go. - The route forwards to
appServer.publishHandlerinmain/handlers_api.go. - The handler unmarshals JSON into
service.PublishRequestand callsXiaohongshuService.PublishContent. PublishContentvalidates input, downloads remote images viaprocessImagesusingdownloader.NewImageProcessor, and builds aPublishImageContentstruct.- The method invokes
publishContent, which creates a fresh Rod browser vianewBrowser()callingbrowser.NewBrowser, and instantiates aPublishActionviaxiaohongshu.NewPublishImageAction. PublishAction.Publishdrives the UI: uploading images, filling title/content fields, setting tags, schedule, visibility settings, and clicking the publish button.- Session state persists through
saveCookiesandcookies.NewLoadCookieto maintain authentication. - The service returns a
PublishResponseJSON 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 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
# 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
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
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. - Dual protocol support enables both RESTful HTTP APIs at
/api/v1/and MCP protocol access at/mcpfor AI tool integration. - Cookie persistence in
main/cookies/cookies.gomaintains login sessions across requests, whilemain/pkg/downloader/images.gohandles remote media preprocessing. - All core automation logic resides in
main/service.goand themain/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 creates a fresh browser via browser.NewBrowser defined in main/browser/browser.go, ensuring isolation between requests. The automation scripts in 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, 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.
How does the system maintain login sessions between requests?
Login persistence is managed through the 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, 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 utilizes downloader.NewImageProcessor from 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.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →