home-server-mcp

anttitane/home-server-mcp Checked 2 days ago

Model Context Protocol (MCP) Server built in C# and .NET 10 for exposing local Home Assistant sensor data to AI Agents.

A production-grade, highly optimized Model Context Protocol (MCP) Server built in C# and .NET 10. This server exposes local Home Assistant sensor data to AI Agents (such as n8n or Claude Desktop) using either the HTTP Streamable standard (stateless POST endpoints) or standard input/output (stdio). This project showcases clean C# architectural patterns, performance-oriented serialization, and LLM-centric API design. This repository highlights senior-level C# engineering and modern architecture practices tailored for AI integrations:

Summary extracted from the README.

Home Assistant MCP Server (.NET 10)

License: MIT .NET Core Protocol Home Assistant

A production-grade, highly optimized Model Context Protocol (MCP) Server built in C# and .NET 10. This server exposes local Home Assistant sensor data to AI Agents (such as n8n or Claude Desktop) using either the HTTP Streamable standard (stateless POST endpoints) or standard input/output (stdio).

This project showcases clean C# architectural patterns, performance-oriented serialization, and LLM-centric API design.


πŸ—οΈ Architecture & AI Developer Highlights

This repository highlights senior-level C# engineering and modern architecture practices tailored for AI integrations:

1. Vertical Slice Architecture (VSA)

Instead of traditional horizontal layers (Repositories, Services, Controllers) that scatter logic across the codebase, this project uses Vertical Slice Architecture.

  • Files are grouped by feature in the Features/ directory.
  • Each slice contains its own requests, responses, registry mapping, and handler logic.
  • High cohesion, low coupling, and easy maintainability.

2. High-Performance Native AOT-Ready JSON Serialization

  • Speaks JSON-RPC 2.0 over standard I/O streams.
  • Uses System.Text.Json Source Generators (McpJsonContext.cs) instead of runtime reflection. This provides:
    • Zero-reflection serialization.
    • Extremely fast startup and execution times.
    • Compatibility with Native AOT compilation for self-contained, lightweight executable distribution.

3. Dual-Transport Support (Stdio & HTTP Streamable Web API)

  • Web API (HTTP Streamable) (Default): Runs a lightweight ASP.NET Core web server on http://localhost:5000 exposing a stateless POST /mcp endpoint, aligning with the modern Streamable HTTP transport standard.
  • Stdio Transport: Triggered by passing the stdio or --stdio flag. Communicates strictly over stdin/stdout with diagnostic logs correctly routed to stderr to avoid stream corruption.

4. Clean C# 14/15 Syntax

  • Primary Constructors to streamline dependency injection.
  • File-Scoped Namespaces to reduce indentation levels.
  • Records and Pattern Matching for robust and immutable DTO representations.

πŸ”„ System Flow

sequenceDiagram
    participant Agent as AI Agent (n8n / Claude)
    participant Mcp as HomeAssistantMcp (stdio)
    participant HA as HomeAssistant (REST API)

    Agent->>Mcp: initialize
    Mcp->>Agent: protocolVersion & capabilities.tools
    Agent->>Mcp: notifications/initialized
    
    Agent->>Mcp: tools/list
    Mcp->>Agent: get_temperature, get_humidity, etc. (based on appsettings)
    
    Agent->>Mcp: tools/call get_temperature (arguments: {entity: "indoor"})
    Mcp->>HA: GET /api/states/sensor.living_room_temperature
    HA->>Mcp: 200 OK (State JSON)
    Mcp->>Agent: ToolCallResult ("Temperature: 22.5 Β°C (sensor.living_room_temperature)")

πŸ› οΈ Project Structure

home-server-mcp/
β”œβ”€β”€ HomeAssistantMcp.csproj
β”œβ”€β”€ appsettings.json           # Environment configurations
β”œβ”€β”€ Program.cs                 # App entry point & DI Bootstrap
β”œβ”€β”€ Infrastructure/            # Shared cross-cutting concerns
β”‚   β”œβ”€β”€ Configuration/
β”‚   β”‚   └── HomeAssistantSettings.cs
β”‚   β”œβ”€β”€ HomeAssistant/
β”‚   β”‚   β”œβ”€β”€ HomeAssistantClient.cs  # REST API Client (GET /api/states/{id})
β”‚   β”‚   └── EntityState.cs          # Home Assistant state DTOs
β”‚   └── Mcp/
β”‚       β”œβ”€β”€ McpJsonContext.cs       # Source Generator for System.Text.Json
β”‚       β”œβ”€β”€ McpRequest.cs           # JSON-RPC Request schema
β”‚       β”œβ”€β”€ McpResponse.cs          # JSON-RPC Response helpers
β”‚       β”œβ”€β”€ McpErrorCodes.cs        # MCP Error Constants
β”‚       └── StdioMcpHost.cs         # Stream Reader loop and Router
└── Features/                  # Vertical Feature Slices
    β”œβ”€β”€ Initialize/
    β”‚   └── InitializeHandler.cs    # Handles protocol handshakes
    β”œβ”€β”€ ListTools/
    β”‚   β”œβ”€β”€ ListToolsHandler.cs     # Lists available sensor tools
    β”‚   └── SensorToolCatalog.cs    # Tool declarations & schemas
    └── GetSensorState/
        β”œβ”€β”€ GetSensorStateHandler.cs# Fetches HA entity state
        └── SensorToolRegistry.cs   # Maps tool name -> Home Assistant Entity ID

βš™οΈ Configuration

The application supports the standard .NET configuration model, loading settings from appsettings.json and optionally overriding them via appsettings.Development.json (which is excluded from Git to prevent secret exposure).

1. Global Configuration (appsettings.json)

Modify the template in appsettings.json:

{
  "HomeAssistant": {
    "BaseUrl": "http://homeassistant.local:8123",
    "LongLivedAccessToken": "YOUR_LONG_LIVED_ACCESS_TOKEN",
    "SensorTypes": {
      "temperature": {
        "Description": "Returns the current indoor temperature reading from Home Assistant.",
        "Entities": {
          "indoor": "sensor.living_room_temperature"
        }
      },
      "humidity": {
        "Description": "Returns the current indoor humidity reading from Home Assistant.",
        "Entities": {
          "living_room": "sensor.living_room_humidity"
        }
      }
    }
  },
  "Mcp": {
    "ServerName": "home-assistant-sensors",
    "ServerVersion": "1.0.0",
    "ProtocolVersion": "2025-06-18"
  }
}
  • LongLivedAccessToken: Generate this in your Home Assistant profile page (at the very bottom).
  • SensorTypes: Define custom sensor types and entities. Each sensor type becomes a tool called get_{sensor_type} (e.g., get_temperature).
    • If a sensor type has only one entity, the tool call's parameter entity is optional.
    • If a sensor type has multiple entities, the tool call's parameter entity is required and is validated against the keys under Entities.

πŸš€ Running and Deploying

Build the Project

Compile the server using the .NET SDK:

dotnet build -c Release

Run in Web API (HTTP Streamable) Mode (Default)

To start the web server listening on http://localhost:5000:

dotnet run
# Or run the binary directly:
bin/Debug/net10.0/HomeAssistantMcp.exe

You can access the health check endpoint at http://localhost:5000/ and POST your JSON-RPC requests directly to http://localhost:5000/mcp.

Run in Stdio Mode

To run in standard I/O mode for desktop/local clients:

dotnet run -- --stdio
# Or run the binary directly:
bin/Debug/net10.0/HomeAssistantMcp.exe --stdio

You can paste the initialization JSON-RPC payload to test:

{"jsonrpc":"2.0","method":"initialize","id":1,"params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test-client","version":"1.0.0"}}}

πŸ”Œ Integration with MCP Clients

1. n8n (Native MCP Client - HTTP Streamable)

The native n8n MCP Client node or MCP Client Tool node can connect directly over the network:

  • Transport: HTTP (Streamable HTTP)
  • URL: http://localhost:5000/mcp

(Note: If running n8n in a Docker container on the same host, use http://host.docker.internal:5000/mcp)

2. n8n (Community Node - Stdio)

If using the community n8n-nodes-mcp node:

  • Transport: STDIO
  • Command: dotnet
  • Arguments: c:\Users\tanekera\source\home-server-mcp\bin\Debug\net10.0\HomeAssistantMcp.dll --stdio

3. Claude Desktop Configuration

Add the following to your claude_desktop_config.json to spawn the server in stdio mode:

{
  "mcpServers": {
    "home-assistant-sensors": {
      "command": "dotnet",
      "args": [
        "c:/Users/tanekera/source/home-server-mcp/bin/Debug/net10.0/HomeAssistantMcp.dll",
        "--stdio"
      ]
    }
  }
}

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.