The Model Context Protocol (MCP) implementation in llama-ui manages the lifecycle of connections to external MCP servers, tool execution, resource management, and prompt operations. The architecture relies on several specialized stores:
mcpStore: The central orchestrator. It manages server configurations, connection states, health checks, and a toolsIndex (mapping tool names to their respective servers). It also handles tool execution and prompt retrieval.mcpResStore (mcpResourceStore): Manages MCP resources, including server resources, cached resource content, subscriptions, and active attachments.MCPSvc (MCPService): The service layer responsible for low-level transport (WebSocket, StreamableHTTP, or SSE) and protocol handshakes with external servers.chatStore: Consumes MCP resources as message extras to provide context to the LLM.
Key Lifecycle Flows
1. Initialization
Upon app startup, mcpStore.ensureInitialized() is called. It retrieves server settings from LocalStorage, parses them, and for each enabled server, initiates a connection via MCPSvc. This process includes a transport handshake, capability exchange, and indexing of available tools and resources.
2. Tool Execution
When a tool is called (e.g., via executeTool(mcpCall)), the mcpStore resolves the correct server using the toolsIndex. It acquires a connection (incrementing activeFlowCount to prevent shutdown during execution), calls the tool via MCPSvc, and formats the result (handling text, images, or embedded resources) before releasing the connection.
3. Resource & Prompt Management
- Prompts:
mcpStore can list all prompts from connected servers or fetch a specific prompt using getPrompt(serverName, promptName, args?). - Resources: Users can add attachments via
mcpResStore.addAttachment(). Content is fetched using mcpStore.readResource(serverName, uri) and cached in the mcpResStore.