Command Palette

Search for a command to run...

UnylyUnyly
Весь каталог

Home Server

БесплатноНе проверен

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

GitHubEmbed

Описание

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

README

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.

from github.com/anttitane/home-server-mcp

Установка Home Server

У этого сервера нет опубликованного пакета — он собирается из исходников. Открой репозиторий и следуй инструкции в README.

▸ github.com/anttitane/home-server-mcp

FAQ

Home Server MCP бесплатный?

Да, Home Server MCP бесплатный — установка в пару кликов через Unyly без оплаты.

Нужен ли API-ключ для Home Server?

Нет, Home Server работает без API-ключей и переменных окружения.

Home Server — hosted или self-hosted?

Self-hosted: сервер запускается локально на твоей машине командой из раздела установки.

Как установить Home Server в Claude Desktop, Claude Code или Cursor?

Открой Home Server на unyly.org, выбери вкладку своего клиента (Claude Desktop, Claude Code, Cursor) и нажми Install — конфиг сгенерируется автоматически, без правки JSON.

Похожие MCP

Compare Home Server with

Не уверен что выбрать?

Найди свой стек за 60 секунд

Автор?

Embed-бейдж для README

Похожее

Все в категории ai