8000 Add MCP server by andig · Pull Request #21936 · evcc-io/evcc · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Add MCP server #21936

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (

"github.com/evcc-io/evcc/core"
"github.com/evcc-io/evcc/core/keys"
"github.com/evcc-io/evcc/mcp"
"github.com/evcc-io/evcc/push"
"github.com/evcc-io/evcc/server"
"github.com/evcc-io/evcc/server/updater"
Expand Down Expand Up @@ -322,6 +323,8 @@ func runRoot(cmd *cobra.Command, args []string) {

httpd.RegisterSiteHandlers(site, valueChan)

httpd.RegisterMcpHandler(mcp.NewHandler(site))

go func() {
site.Run(stopC, conf.Interval)
}()
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ require (
github.com/lorenzodonini/ocpp-go v0.19.0
github.com/lunixbochs/struc v0.0.0-20241101090106-8d528fa2c543
github.com/mabunixda/wattpilot v1.8.4
github.com/mark3labs/mcp-go v0.32.0
github.com/mitchellh/go-homedir v1.1.0
github.com/muka/go-bluetooth v0.0.0-20240701044517-04c4f09c514e
github.com/mxschmitt/golang-combinations v1.2.0
Expand Down Expand Up @@ -205,6 +206,7 @@ require (
github.com/teivah/onecontext v1.3.0 // indirect
github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
gitlab.com/c0b/go-ordered-json v0.0.0-20201030195603-febf46534d5a // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/mod v0.24.0 // indirect
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,8 @@ github.com/lunixbochs/struc v0.0.0-20241101090106-8d528fa2c543/go.mod h1:vy1vK6w
github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ=
github.com/mabunixda/wattpilot v1.8.4 h1:nPwTQft15JeRJDUoxv6IpsGpu45EvNGW3EFU6UHNUzc=
github.com/mabunixda/wattpilot v1.8.4/go.mod h1:oXWlvKInaVt8FFSdEoNObEP5N8+4m6cbiF11M+8DAHY=
github.com/mark3labs/mcp-go v0.32.0 h1:fgwmbfL2gbd67obg57OfV2Dnrhs1HtSdlY/i5fn7MU8=
github.com/mark3labs/mcp-go v0.32.0/go.mod h1:rXqOudj/djTORU/ThxYx8fqEVj/5pvTuuebQ2RC7uk4=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
Expand Down Expand Up @@ -710,6 +712,8 @@ github.com/volkszaehler/mbmd v0.0.0-20250524200024-23178706aaf1/go.mod h1:egeAZt
github.com/writeas/go-strip-markdown/v2 v2.1.1 h1:hAxUM21Uhznf/FnbVGiJciqzska6iLei22Ijc3q2e28=
github.com/writeas/go-strip-markdown/v2 v2.1.1/go.mod h1:UvvgPJgn1vvN8nWuE5e7v/+qmDu3BSVnKAB6Gl7hFzA=
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
gitlab.com/bboehmke/sunny v0.16.0 h1:arcU5MNupJ9KELOcSC82mYPGP/friBop+PxtybhqRwo=
Expand Down 8000
24 changes: 24 additions & 0 deletions mcp/helper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package mcp

import (
"strconv"
"strings"
)

func extractID(uri string) string {
// Extract the ID from the URI, e.g., "loadpoints://123" -> "123"
parts := strings.Split(uri, "://")
if len(parts) < 2 {
return ""
}
return parts[1]
}

func extractNumericID(uri string) int {
s := extractID(uri)
if s == "" {
return 0
}
id, _ := strconv.Atoi(s)
return id
}
47 changes: 47 additions & 0 deletions mcp/loadpoint.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package mcp

import (
"context"
"encoding/json"
"errors"

"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/core/site"
"github.com/mark3labs/mcp-go/mcp"
)

func loadpointStatusHandler(site site.API) func(ctx context.Context, req mcp.ReadResourceRequest) ([]mcp.ResourceContents, error) {
return func(ctx context.Context, req mcp.ReadResourceRequest) ([]mcp.ResourceContents, error) {
lpid := extractNumericID(req.Params.URI) // "users://123" -> "123"

if lpid == 0 || lpid > len(site.Loadpoints()) {
return nil, errors.New("invalid loadpoint ID")
}

lp := site.Loadpoints()[lpid-1] // Loadpoint IDs are 1-based
status := lp.GetStatus()

data := struct {
Title string `json:"title"`
Connected bool `json:"connected,omitempty"`
Charging bool `json:"charging,omitempty"`
}{
Title: lp.GetTitle(),
Connected: status == api.StatusB || status == api.StatusC,
Charging: status == api.StatusC,
}

jsonData, err := json.Marshal(data)
if err != nil {
return nil, err
}

return []mcp.ResourceContents{
mcp.TextResourceContents{
URI: req.Params.URI,
MIMEType: "application/json",
Text: string(jsonData),
},
}, nil
}
}
15 changes: 15 additions & 0 deletions mcp/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package mcp

import "github.com/evcc-io/evcc/util"

type logAdapter struct {
log *util.Logger
}

func (l *logAdapter) Infof(format string, args ...interface{}) {
l.log.INFO.Printf(format, args...)
}

func (l *logAdapter) Errorf(format string, args ...interface{}) {
l.log.ERROR.Printf(format, args...)
}
65 changes: 65 additions & 0 deletions mcp/mcp.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package mcp

import (
"net/http"

"github.com/evcc-io/evcc/core/site"
"github.com/evcc-io/evcc/util"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)

func NewHandler(site site.API) http.Handler {
log := util.NewLogger("mcp")

// Create a new MCP server
s := server.NewMCPServer(
"evcc ☀️🚘",
util.Version,
server.WithToolCapabilities(true),
)

s.AddResource(
mcp.NewResource(
"https://docs.evcc.io",
"docs",
mcp.WithResourceDescription("evcc documentation"),
),
nil, // TODO no handler needed
)

s.AddTool(
mcp.NewTool(
"site-loadpoints",
mcp.WithDescription("Number of loadpoints"),
mcp.WithReadOnlyHintAnnotation(true),
),
loadpointsHandler(site),
)

s.AddTool(
mcp.NewTool(
"solar-forecast",
mcp.WithDescription("Solar forecast for remaining production today"),
mcp.WithReadOnlyHintAnnotation(true),
),
solarForecastHandler(site),
)

s.AddResource(
mcp.NewResource(
"loadpoints://{loadpoint_id}",
"loadpoint-status",
mcp.WithResourceDescription("Loadpoint status information"),
mcp.WithMIMEType("application/json"),
),
loadpointStatusHandler(site),
)

ss := server.NewStreamableHTTPServer(s,
server.WithLogger(&logAdapter{log}),
server.WithEndpointPath("/"),
)

return ss
}
46 changes: 46 additions & 0 deletions mcp/site.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package mcp

import (
"context"
"errors"
"fmt"
"strconv"
"time"

"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/core/site"
"github.com/evcc-io/evcc/tariff"
"github.com/jinzhu/now"
"github.com/mark3labs/mcp-go/mcp"
)

func loadpointsHandler(site site.API) func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
count := len(site.Loadpoints())
return mcp.NewToolResultText(strconv.Itoa(count)), nil
}
}

func solarForecastHandler(site site.API) func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
solar := site.GetTariff(api.TariffUsageSolar)
if solar == nil {
return nil, errors.New("solar tariff not found")
}

rates := tariff.Forecast(solar)
if len(rates) == 0 {
return nil, errors.New("solar forecast data not available")
}

// TODO use global function
var total float64
for _, rate := range rates {
if rate.Start.After(time.Now()) && !rate.End.After(now.EndOfDay()) {
total += rate.Value * rate.End.Sub(rate.Start).Hours() // Wh
}
}

return mcp.NewToolResultText(fmt.Sprintf("%.2f kWH", total/1e3)), nil
}
}
Loading
Loading
0